Objective-c – Get RGB value from UIColor presets

cgcolorspaceiphoneobjective cuicolor

I my application I pass RGB color value to server. My app uses UIColor predefined values, like [UIColor grayColor], [UIColor redColor]. I know that I can use following code:

const CGFloat *c = CGColorGetComponents(color.CGColor)

but only for colors that are in RBG color space, however, [UIColor grayColor] is not.

Is there any way to get RGB values for non-RBG colors?

Thanks!

Best Answer

UIColor has a method which gives you the RGB components (-getRed:green:blue:alpha:) which works great on iOS 7 or higher. On iOS 6 and earlier, this method will fail and return NO if the color is not in an RGB color space (as it will for [UIColor grayColor].)

For iOS 6 and earlier, the only way I know of for doing this that works in all color spaces is to create a Core Graphics bitmap context in an RGB color space and draw into it with your color. You can then read out the RGB values from the resulting bitmap. Note that this won't work for certain colors, like pattern colors (eg. [UIColor groupTableViewBackgroundColor]), which don't have reasonable RGB values.

- (void)getRGBComponents:(CGFloat [3])components forColor:(UIColor *)color {
    CGColorSpaceRef rgbColorSpace = CGColorSpaceCreateDeviceRGB();
    unsigned char resultingPixel[4];
    CGContextRef context = CGBitmapContextCreate(&resultingPixel,
                                                 1,
                                                 1,
                                                 8,
                                                 4,
                                                 rgbColorSpace,
                                                 kCGImageAlphaNoneSkipLast);
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, CGRectMake(0, 0, 1, 1));
    CGContextRelease(context);
    CGColorSpaceRelease(rgbColorSpace);

    for (int component = 0; component < 3; component++) {
        components[component] = resultingPixel[component] / 255.0f;
    }
}

You can use it something like this:

    CGFloat components[3];
    [self getRGBComponents:components forColor:[UIColor grayColor]];
    NSLog(@"%f %f %f", components[0], components[1], components[2]);
Related Topic