CGColorGetComponents有问题吗?
当我使用从UIColor
返回的CGColor
调用CGColorGetComponents
, 除了白色和黑色之外 ,它似乎可以正常工作。
这是代码…
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]);
这个日志
r=1.000000, g=1.000000, b=0.000000, a=0.000000
注意B和A都是零,而不是一个。
如果你replace其他颜色,如redColor,blueColor等,它的工作原理…的RGB和A值设置为人们所期望的。 但是,黑色和白色再次产生奇怪的结果。 有这个function有问题,还是有一些解决方法/任务,我应该做的?
[UIColor whiteColor]
和[UIColor blackColor]
使用[UIColor colorWithWhite:alpha:]
创buildUIColor。 这意味着这个CGColorRef只有2个颜色组件,而不是4个像使用[UIColor colorWithRed:green:blue:alpha:]
创build的颜色。
当然你也可以NSLog。
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?"); }
请注意,也有不同的颜色空间。 所以,如果你需要这个代码不只是日志logging(例如,保存RGBAstring到JSON),你必须检查(也可能转换)的颜色空间。