Is there an easy way to convert UIColor
to a hexadecimal value ?
Or do we have to get the RGB components with CGColorGetComponents
and then work it
Other than the widely used string based solution, here's a hex (integer) based solution. Usage:
UIColor* color = lf_rgb(0x120aef);
log(@"color %.6x", color.hex_rgb);
And you'll get "color 120aef". I'll put these code in https://github.com/superarts/LCategory, or you can copy-paste into your own code bank too:
#define lf_rgb(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]
@interface UIColor (lc_rgb)
- (NSInteger)hex_rgb;
@end
@implementation UIColor (lc_rgb)
- (NSInteger)hex_rgb
{
CGFloat r, g, b, a;
BOOL result = [self getRed:&r green:&g blue:&b alpha:&a];
// log(@"rgba: %f, %f, %f, %f", r * 255, g * 255, b * 255, a * 255);
if ((result == NO) || (a != 1.0f))
return -1;
return
(NSInteger)(r * 255) * 256 * 256 +
(NSInteger)(g * 255) * 256 +
(NSInteger)(b * 255) * 1;
}
@end