IOS 十六进制字符串转换成UIColor

时间:2021-07-20 10:14:10
/**
* 十六进制转换成UIColor
*
* @param stringToConvert 十六进制字符串
*
* @return UIColor
*/
+(UIColor *) hexStringToColor: (NSString *) stringToConvert
{
NSString *cString = [[stringToConvert stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
// String should be 6 or 8 characters if ([cString length] < ) return [UIColor blackColor];
// strip 0X if it appears
if ([cString hasPrefix:@"0X"]) cString = [cString substringFromIndex:];
if ([cString hasPrefix:@"#"]) cString = [cString substringFromIndex:];
if ([cString length] != ) return [UIColor blackColor]; // Separate into r, g, b substrings NSRange range;
range.location = ;
range.length = ;
NSString *rString = [cString substringWithRange:range];
range.location = ;
NSString *gString = [cString substringWithRange:range];
range.location = ;
NSString *bString = [cString substringWithRange:range];
// Scan values
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];
}