Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIColor to Hexadecimal (web color)

Tags:

ios

uikit

uicolor

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 ?

like image 949
fes Avatar asked Dec 31 '11 17:12

fes


1 Answers

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!

like image 64
Luc Wollants Avatar answered Sep 21 '22 00:09

Luc Wollants