How to convert colors from one color space to another?

故事扮演 提交于 2019-11-29 09:13:50

I'm not sure how to automatically convert them, but to identify different color spaces you can get the CGColorSpaceModel from the color's CGColorSpaceRef:

UIColor* color = some color;
CGColorSpaceRef colorSpace = CGColorGetColorSpace([color CGColor]);
CGColorSpaceModel colorSpaceModel = CGColorSpaceGetModel(colorSpace);

Then you can compare colorSpaceModel with the constants defined in CoreGraphics/CGColorSpace.h. UIColor's getRed:green:blue:alpha works for kCGColorSpaceModelRGB, whereas getWhite:alpha works for kCGColorSpaceModelMonochrome.

Note that a UIColor that was created with colorWithHue:saturation:brightness:alpha: will actually be in the RGB color space.

For colors created using [UIColor colorWithRed:green:blue:alpha:], you can use UIColor getRed:green:blue:alpha:, described in UIColor Class Reference. It's part of iOS 5 and later.

If the color was created with colorWithWhite:alpha: you can use the getWhite:alpha: instead, described in UIColor Class Reference.

To determine which color space is being used, you can use CGColorGetColorSpace([color colorSpace]). But it's probably easier to just check the result of the method call, then fail over to the next attempt. Something like this:

if ([color getRed:&red green:&green blue:&blue alpha:&alpha]) {
    // red, green and blue are all valid
} else if if ([color getWhite:&white alpha:&alpha]) {
    red = white; green = white; blue = white;
} else {
    // can't get it
}

I don't know how to handle color constants such as [UIColor lightGrayColor], other than drawing them to a temporary bitmap and detecting them. Some of these color constants are actually textures; your best bet is probably to avoid them.

If you plan on doing this a lot, it's an appropriate use of a category:

@interface UIColor(sf)
- (BOOL)sfGetRed:(CGFloat *)red green:(CGFloat *)green blue:(CGFloat *)blue alpha:(CGFloat *)alpha;
@end

@implementation UIColor(sf)
- (BOOL)sfGetRed:(CGFloat *)red green:(CGFloat *)green blue:(CGFloat *)blue alpha:(CGFloat *)alpha {
    if ([self getRed:red green:green blue:blue alpha:alpha]) return YES;
    CGFloat white;
    if ([self getWhite:&white alpha:alpha]) {
        if (red) *red = white;
        if (green) *green = white;
        if (blue) *blue = white;
        return YES;
    }
    return NO;
}
@end

In swift 3 we can directly use

 let colorSpace = uiColor.cgColor.colorSpace
 let csModel = colorSpace.model

to get the color space and color space model from a UIColor.

Jesse Rusak

Another way to convert these is by drawing them into contexts and letting core graphics do the conversion for you. See my answer to this question:

Get RGB value from UIColor presets

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!