I have an RGB hex code like #ffffff as NSString and want to convert that into an UIColor. Is there a simple way to do that?
In some code of mine, I use 2 different functions:
void SKScanHexColor(NSString * hexString, float * red, float * green, float * blue, float * alpha) {
NSString *cleanString = [hexString stringByReplacingOccurrencesOfString:@"#" withString:@""];
if([cleanString length] == 3) {
cleanString = [NSString stringWithFormat:@"%@%@%@%@%@%@",
[cleanString substringWithRange:NSMakeRange(0, 1)],[cleanString substringWithRange:NSMakeRange(0, 1)],
[cleanString substringWithRange:NSMakeRange(1, 1)],[cleanString substringWithRange:NSMakeRange(1, 1)],
[cleanString substringWithRange:NSMakeRange(2, 1)],[cleanString substringWithRange:NSMakeRange(2, 1)]];
}
if([cleanString length] == 6) {
cleanString = [cleanString stringByAppendingString:@"ff"];
}
unsigned int baseValue;
[[NSScanner scannerWithString:cleanString] scanHexInt:&baseValue];
if (red) { *red = ((baseValue >> 24) & 0xFF)/255.0f; }
if (green) { *green = ((baseValue >> 16) & 0xFF)/255.0f; }
if (blue) { *blue = ((baseValue >> 8) & 0xFF)/255.0f; }
if (alpha) { *alpha = ((baseValue >> 0) & 0xFF)/255.0f; }
}
And then I use it like this:
UIColor * SKColorFromHexString(NSString * hexString) {
float red, green, blue, alpha;
SKScanHexColor(hexString, &red, &green, &blue, &alpha);
return [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
}
If you prefer to use this as a UIColor
category, then it's just a matter of altering a few lines:
+ (UIColor *) colorFromHexString:(NSString *)hexString {
NSString *cleanString = [hexString stringByReplacingOccurrencesOfString:@"#" withString:@""];
if([cleanString length] == 3) {
cleanString = [NSString stringWithFormat:@"%@%@%@%@%@%@",
[cleanString substringWithRange:NSMakeRange(0, 1)],[cleanString substringWithRange:NSMakeRange(0, 1)],
[cleanString substringWithRange:NSMakeRange(1, 1)],[cleanString substringWithRange:NSMakeRange(1, 1)],
[cleanString substringWithRange:NSMakeRange(2, 1)],[cleanString substringWithRange:NSMakeRange(2, 1)]];
}
if([cleanString length] == 6) {
cleanString = [cleanString stringByAppendingString:@"ff"];
}
unsigned int baseValue;
[[NSScanner scannerWithString:cleanString] scanHexInt:&baseValue];
float red = ((baseValue >> 24) & 0xFF)/255.0f;
float green = ((baseValue >> 16) & 0xFF)/255.0f;
float blue = ((baseValue >> 8) & 0xFF)/255.0f;
float alpha = ((baseValue >> 0) & 0xFF)/255.0f;
return [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
}
This will handle strings like "#abc", "#abcdef31", etc.