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 out from there?
e.g CGColorGetComponents(color.CGColor)[0] * 256
?
I also had to convert a UIColor to its hex components.
As already pointed out by lewiguez there is a very good category at github that does all that stuff.
But because I wanted to learn how it is done I made my own simple implementation for RGB colours.
+ (NSString*)colorToWeb:(UIColor*)color
{
NSString *webColor = nil;
// This method only works for RGB colors
if (color &&
CGColorGetNumberOfComponents(color.CGColor) == 4)
{
// Get the red, green and blue components
const CGFloat *components = CGColorGetComponents(color.CGColor);
// These components range from 0.0 till 1.0 and need to be converted to 0 till 255
CGFloat red, green, blue;
red = roundf(components[0] * 255.0);
green = roundf(components[1] * 255.0);
blue = roundf(components[2] * 255.0);
// Convert with %02x (use 02 to always get two chars)
webColor = [[NSString alloc]initWithFormat:@"%02x%02x%02x", (int)red, (int)green, (int)blue];
}
return webColor;
}
All feedback is welcome!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With