1

Trying to retrieve RGB values from a UIColor. However, -[UIColor getRed:blue:green:alpha] is not working in my case. The method never returns YES which I think means that the color is not convertible into RGB. I assume this is because my UIColor was generated from a Hex color (ex: #CCCCCC).

How the heck do you get RGB values from hex-based UIColors in iOS?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
eric
  • 4,863
  • 11
  • 41
  • 55
  • [http://stackoverflow.com/questions/1099569/how-to-convert-colors-from-one-color-space-to-another][1] [1]: http://stackoverflow.com/questions/1099569/how-to-convert-colors-from-one-color-space-to-another – Merlevede Feb 06 '14 at 16:43

1 Answers1

4

The problem is with the example you give. The color #CCCCCC is a greyscale color meaning the UIColor is not created with RGB but with a grey. In other words, it is created with UIColor colorWithWhite:alpha:. Since your UIColor is created with a different color model than RGB, using getRed:green:blue:alpha: returns NO.

What you can do is this:-

UIColor *color =  // your color
CGFloat red, green, blue, alpha;

if (![color getRed:&red green:&green blue:&blue alpha:&alpha]) {

    CGFloat white;
    if ([color getWhite:&white alpha:&alpha]) {
        red = green = blue = white;
    } else {
        NSLog(@"Uh oh, not RGB or greyscale");
    }
}

Update:

It seems that the behavior changed a bit as of iOS 8. The RGB values of a color created with UIColor colorWithWhite:alpha: can be obtained with UIColor getRed:green:blue:alpha:. In earlier versions of iOS, this didn't work. Hence the need for the code I originally posted.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • Thanks for the solution. It still makes zero sense to me why we're not able to get the RGB values for ANY color (regardless of how it was generated) but whatev.. – eric Feb 06 '14 at 16:50
  • Read the docs for the method. It only works for colors created with the RGB color space. Some of your colors are created with a greyscale color space. Keep in mind that convert from other color spaces to RGB is not always lossless. For example, going from HSB to RGB is not exact. – rmaddy Feb 06 '14 at 16:52
  • I tried this and it doesnt work: `UIColor * color =[UIColor colorWithWhite:0.9 alpha:1.0]; CGFloat red, green, blue, alpha; if (![color getRed:&red green:&green blue:&blue alpha:&alpha]) { CGFloat white; if ([color getWhite:&white alpha:&alpha]) { red = green = blue = white; NSLog(@"r %f g %f b %f white %f",red,green,blue,white); } else { NSLog(@"Uh oh, not RGB or greyscale"); } }` – DevC Jan 26 '15 at 16:12
  • Apologies, nothing gets printed. – DevC Jan 26 '15 at 16:17
  • 1
    @DevC Log the red, green, blue values at the end, not in the middle. – rmaddy Jan 26 '15 at 16:21
  • 1
    @DevC It seems that as of iOS 8, using `UIColor getRed:green:blue:alpha:` works even with grayscale colors created with `UIColor colorWithWhite:alpha:`. – rmaddy Jan 26 '15 at 16:27