Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
327 views
in Technique[技术] by (71.8m points)

iphone - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

[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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...