I've found the simplest way to do this is with a macro. Just include it in your header and it's available throughout your project.
#define UIColorFromRGB(rgbValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]
uicolor macro with hex values
Also formatted version of this code:
#define UIColorFromRGB(rgbValue) \
[UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 \
green:((float)((rgbValue & 0x00FF00) >> 8))/255.0 \
blue:((float)((rgbValue & 0x0000FF) >> 0))/255.0 \
alpha:1.0]
Usage:
label.textColor = UIColorFromRGB(0xBC1128);
Swift:
static func UIColorFromRGB(_ rgbValue: Int) -> UIColor! {
return UIColor(
red: CGFloat((Float((rgbValue & 0xff0000) >> 16)) / 255.0),
green: CGFloat((Float((rgbValue & 0x00ff00) >> 8)) / 255.0),
blue: CGFloat((Float((rgbValue & 0x0000ff) >> 0)) / 255.0),
alpha: 1.0)
}
UIColor has a method which gives you the RGB components (-getRed:green:blue:alpha:
) which works great on iOS 7 or higher. On iOS 6 and earlier, this method will fail and return NO
if the color is not in an RGB color space (as it will for [UIColor grayColor]
.)
For iOS 6 and earlier, the only way I know of for doing this that works in all color spaces is to create a Core Graphics bitmap context in an RGB color space and draw into it with your color. You can then read out the RGB values from the resulting bitmap. Note that this won't work for certain colors, like pattern colors (eg. [UIColor groupTableViewBackgroundColor]), which don't have reasonable RGB values.
- (void)getRGBComponents:(CGFloat [3])components forColor:(UIColor *)color {
CGColorSpaceRef rgbColorSpace = CGColorSpaceCreateDeviceRGB();
unsigned char resultingPixel[4];
CGContextRef context = CGBitmapContextCreate(&resultingPixel,
1,
1,
8,
4,
rgbColorSpace,
kCGImageAlphaNoneSkipLast);
CGContextSetFillColorWithColor(context, [color CGColor]);
CGContextFillRect(context, CGRectMake(0, 0, 1, 1));
CGContextRelease(context);
CGColorSpaceRelease(rgbColorSpace);
for (int component = 0; component < 3; component++) {
components[component] = resultingPixel[component] / 255.0f;
}
}
You can use it something like this:
CGFloat components[3];
[self getRGBComponents:components forColor:[UIColor grayColor]];
NSLog(@"%f %f %f", components[0], components[1], components[2]);
Best Answer
In some code of mine, I use 2 different functions:
And then I use it like this:
If you prefer to use this as a
UIColor
category, then it's just a matter of altering a few lines:This will handle strings like "#abc", "#abcdef31", etc.