iphonequartz-graphicscgcolorcgcolorspace

How to get color components of a CGColor correctly


I have a UILabel with black color;

i am writing the following code to get black color's components.

UIColor *aColor = [aLabel.textColor retain];
const CGFloat* components = CGColorGetComponents(aColor.CGColor);
CGColorSpaceRef colorSpace=CGColorSpaceCreateDeviceRGB();

but always this is giving Green color components instead of black color components;

Is any one have idea about this?

Am i passing different color space?

:-( Please help me.


Solution

  • Most likely wrong colorspace. I guess the alpha component of the grayscale colorspace gets where you think the green component should be.
    I use this function to create a string from UIColor, I only encounter RGB and Grayscale colorspaces, so I just interpret every color with less than 4 (R+G+B+A) components as grayscale.

    if (CGColorGetNumberOfComponents(color.CGColor) < 4) {
        const CGFloat *components = CGColorGetComponents(color.CGColor);
        color = [UIColor colorWithRed:components[0] green:components[0] blue:components[0] alpha:components[1]];
    }
    if (CGColorSpaceGetModel(CGColorGetColorSpace(color.CGColor)) != kCGColorSpaceModelRGB) {
        NSLog(@"no rgb colorspace");
        // do seomthing
    }
    const CGFloat *components = CGColorGetComponents(color.CGColor);
    NSString *colorAsString = [NSString stringWithFormat:@"%f,%f,%f,%f", components[0], components[1], components[2], components[3]];
    

    of course this method is not save for all cases, you should adopt it to your requirements.