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?
[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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With