当前位置: 代码迷 >> 综合 >> iOS-工具方法-UIColor
  详细解决方案

iOS-工具方法-UIColor

热度:70   发布时间:2023-12-18 12:08:50.0

根据十六进制字符串转颜色

///字符串转颜色
+(UIColor *)colorWithHexString:(NSString *) stringToConvert{NSString *cString = [[stringToConvert stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];if ([cString length] < 6){return [UIColor whiteColor];}if ([cString hasPrefix:@"#"]){cString = [cString substringFromIndex:1];}if ([cString length] != 6){return [UIColor whiteColor];}NSRange range;range.location = 0;range.length = 2;NSString *rString = [cString substringWithRange:range];range.location = 2;NSString *gString = [cString substringWithRange:range];range.location = 4;NSString *bString = [cString substringWithRange:range];unsigned int r, g, b;[[NSScanner scannerWithString:rString] scanHexInt:&r];[[NSScanner scannerWithString:gString] scanHexInt:&g];[[NSScanner scannerWithString:bString] scanHexInt:&b];return [UIColor colorWithRed:((float) r / 255.0f)green:((float) g / 255.0f)blue:((float) b / 255.0f)alpha:1.0f];
}

UIColor转换成UIImage

///将UIColor变换为UIImage
+ (UIImage *)createImageWithColor:(UIColor *)color
{CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);UIGraphicsBeginImageContext(rect.size);CGContextRef context = UIGraphicsGetCurrentContext();CGContextSetFillColorWithColor(context, [color CGColor]);CGContextFillRect(context, rect);UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();UIGraphicsEndImageContext();return theImage;
}