Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top