从UIColor预设中获取RGB值 [英] Get RGB value from UIColor presets

查看:146
本文介绍了从UIColor预设中获取RGB值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序我将RGB颜色值传递给服务器。我的应用程序使用UIColor预定义值,如[UIColor grayColor],[UIColor redColor]。我知道我可以使用以下代码:

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)

但仅适用于RBG色彩空间中的颜色,但是,[UIColor grayColor]不是。

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

有没有办法获得非RBG颜色的RGB值?

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

谢谢!

推荐答案

UIColor有一个方法可以为你提供RGB组件( -getRed:green:blue:alpha:)适用于iOS 7或更高版本。在iOS 6及更早版本中,如果颜色不在RGB颜色空间中,此方法将失败并返回 NO (因为它将用于 [UIColor grayColor] ] 。)

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

对于iOS 6及更早版本,我知道这样做的唯一方法是在所有颜色空间中工作,就是创建一个RGB颜色空间中的Core Graphics位图上下文,并使用您的颜色绘制它。然后,您可以从生成的位图中读出RGB值。请注意,这不适用于某些颜色,例如图案颜色(例如[UIColor groupTableViewBackgroundColor]),它们没有合理的RGB值。

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;
    }
}

您可以使用以下内容:

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

这篇关于从UIColor预设中获取RGB值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆