Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert a UIColor to a hexadecimal string?

I have a project where I need to store the RGBA values of a UIColor in a database as an 8-character hexadecimal string. For example, [UIColor blueColor] would be @"0000FFFF". I know I can get the component values like so:

CGFloat r,g,b,a;
[color getRed:&r green:&g blue: &b alpha: &a];

but I don't know how to go from those values to the hex string. I've seen a lot of posts on how to go the other way, but nothing functional for this conversion.

like image 439
Josh Wight Avatar asked Aug 09 '12 13:08

Josh Wight


1 Answers

Get your floats converted to int values first, then format with stringWithFormat:

    int r,g,b,a;

    r = (int)(255.0 * rFloat);
    g = (int)(255.0 * gFloat);
    b = (int)(255.0 * bFloat);
    a = (int)(255.0 * aFloat);

    [NSString stringWithFormat:@"%02x%02x%02x%02x", r, g, b, a];
like image 141
CSmith Avatar answered Oct 11 '22 16:10

CSmith