Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
559 views
in Technique[技术] by (71.8m points)

iphone - Get RGB value from UIColor presets

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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]);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...