Getting RGB values from UIColors derived from Hex colors

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?

Answers


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.


Need Your Help

com.android.dex.DexException: Multiple dex files define Lcom/google/android/gms/analytics/internal/Command$1;

android google-analytics

I am developing android app in Android Studio. I have to add Google Analytics in my app and did everything related to that but when I try to run my project I am getting this error:

Change One Word's Weight in a H1 CSS

html css text positioning

I've been trying to find out how to do the following for quite some time now. Obviously, I can solve this problem by having different h1s and position them, but I want to know if I can solve this p...