Extract HEX (RGB) color from UIColor

Simple function to extract HEX (RGB) color from UIColor

Important notes:
1. Function checks the color components number (in case of monochrome color model)
2. Function supports RGB color space model only – otherwise returns black color

– (NSString *) htmlFromUIColor:(UIColor *)_color {

if (CGColorGetNumberOfComponents(_color.CGColor) < 4) {

const CGFloat *components = CGColorGetComponents(_color.CGColor);

_color = [UIColor colorWithRed:components[0] green:components[0] blue:components[0] alpha:components[1]];

}

if (CGColorSpaceGetModel(CGColorGetColorSpace(_color.CGColor)) != kCGColorSpaceModelRGB) {

return [NSString stringWithFormat:@”#FFFFFF”];

}

return [NSString stringWithFormat:@”#%02X%02X%02X”, (int)((CGColorGetComponents(_color.CGColor))[0]*255.0), (int)((CGColorGetComponents(_color.CGColor))[1]*255.0), (int)((CGColorGetComponents(_color.CGColor))[2]*255.0)];

}