6

Please can you tell me how I can convert an RGB UIColor to a Hexadecimal HTML color code string?

max_
  • 24,076
  • 39
  • 122
  • 211

1 Answers1

16
- (NSString *)getHexStringForColor:(UIColor*)color {
    const CGFloat *components = CGColorGetComponents(color.CGColor);
    CGFloat r = components[0];
    CGFloat g = components[1];
    CGFloat b = components[2];

    return [NSString stringWithFormat:@"%02X%02X%02X", (int)(r * 255), (int)(g * 255), (int)(b * 255)];
}
ThomasW
  • 16,981
  • 4
  • 79
  • 106
taskinoor
  • 45,586
  • 12
  • 116
  • 142
  • 2
    Unfortunately, this doesn't work with non-RGB colors like `[UIColor blackColor]`. The question is only about RGB colors, but if you want to support more `UIColor`s you can use ngb's approach here: http://stackoverflow.com/a/13134326/211292 – ThomasW May 22 '14 at 09:22