13

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.

Josh Wight
  • 182
  • 1
  • 2
  • 8

3 Answers3

22

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];
Christian
  • 357
  • 3
  • 13
CSmith
  • 13,318
  • 3
  • 39
  • 42
  • I've tried suggestions similar to this before, but this one actually worked. – Josh Wight Aug 09 '12 at 13:23
  • Method getRed:green:blue:alpha: is only on iOS 5+. What about iOS 4? – Tony Oct 02 '13 at 07:00
  • 1
    And a good method for doing the reverse conversion (like if you're storing/loading colors from a database / Core Data) can be found here - http://stackoverflow.com/a/12397366/553394 – Eric G Mar 01 '14 at 01:04
  • 2
    Keep in mind that calling `getRed:green:blue;alpha:` will fail with non-RGB colors such as `[UIColor grayColor]` or `[UIColor whiteColor]`. So this solution only works for some colors. – rmaddy Jan 23 '15 at 17:31
14

Here it goes. Returns a NSString (e.g. ffa5678) with a hexadecimal value of the color.

- (NSString *)hexStringFromColor:(UIColor *)color
{
    const CGFloat *components = CGColorGetComponents(color.CGColor);

    CGFloat r = components[0];
    CGFloat g = components[1];
    CGFloat b = components[2];

    return [NSString stringWithFormat:@"%02lX%02lX%02lX",
            lroundf(r * 255),
            lroundf(g * 255),
            lroundf(b * 255)];
}
Rafał Sroka
  • 39,540
  • 23
  • 113
  • 143
  • Try this with `[UIColor grayColor]` (or any other non-RGB color). Bad results or possible a crash! – rmaddy Jan 23 '15 at 17:31
1

Swift 4 answer by extension UIColor:

extension UIColor {
    var hexString: String {
        let colorRef = cgColor.components
        let r = colorRef?[0] ?? 0
        let g = colorRef?[1] ?? 0
        let b = ((colorRef?.count ?? 0) > 2 ? colorRef?[2] : g) ?? 0
        let a = cgColor.alpha
    
        var color = String(
            format: "#%02lX%02lX%02lX",
            lroundf(Float(r * 255)),
            lroundf(Float(g * 255)),
            lroundf(Float(b * 255))
        )
        if a < 1 {
            color += String(format: "%02lX", lroundf(Float(a * 255)))
        }
        return color
    }
}
E. Bogren
  • 118
  • 1
  • 9