Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an issue with CGColorGetComponents?

When I call CGColorGetComponents with the CGColor returned from a UIColor, it seems to work properly except with white and black.

Here's the code...

CGColorRef myColorRef = [[UIColor whiteColor] CGColor];

const CGFloat * colorComponents = CGColorGetComponents(myColorRef);

NSLog(@"r=%f, g=%f, b=%f, a=%f",
    colorComponents[0],
    colorComponents[1],
    colorComponents[2],
    colorComponents[3]);

This logs

r=1.000000, g=1.000000, b=0.000000, a=0.000000

Note both B and A are zero, not one.

If you substitute other colors like redColor, blueColor, etc., it works... the RGB and A values are set as one would expect. But again, black and white produce odd results. Is there some issue with this function or is there some workaround/task I should be doing?

like image 833
Mark A. Donohoe Avatar asked Feb 11 '12 08:02

Mark A. Donohoe


1 Answers

[UIColor whiteColor] and [UIColor blackColor] use [UIColor colorWithWhite:alpha:] to create the UIColor. Which means this CGColorRef has only 2 color components, not 4 like colors created with [UIColor colorWithRed:green:blue:alpha:].

Of course you can NSLog those too.

if (CGColorGetNumberOfComponents(myColorRef) == 2) {
    const CGFloat *colorComponents = CGColorGetComponents(myColorRef);
    NSLog(@"r=%f, g=%f, b=%f, a=%f", colorComponents[0], colorComponents[0], colorComponents[0], colorComponents[1]);
}
else if (CGColorGetNumberOfComponents(myColorRef) == 4) {
    const CGFloat * colorComponents = CGColorGetComponents(myColorRef);
    NSLog(@"r=%f, g=%f, b=%f, a=%f", colorComponents[0], colorComponents[1], colorComponents[2], colorComponents[3]);
}
else {
    NSLog(@"What is this?");
}

Be aware that there are different colorSpaces too. So if you need this code for more than logging (e.g. saving RGBA strings to json) you have to check (and probably convert) the colorSpace too.

like image 173
Matthias Bauch Avatar answered Nov 02 '22 00:11

Matthias Bauch