获取某些 UIColors 的颜色分量时出现异常结果
我正在尝试提取 UIColor
的 rgb 组件,以便在 CGBitmapContext
中手动构建像素。 以下示例代码适用于大多数 UIColor
常量,但令人困惑的是,并非全部。 也就是说:
CGColorRef color = [[UIColor yellowColor] CGColor];
const float* rgba = CGColorGetComponents(color);
float r = rgba[0];
float g = rgba[1];
float b = rgba[2];
float a = rgba[3];
NSLog( @"r=%f g=%f b=%f a=%f", r, g, b, a);
上面 [UIColor YellowColor]
的结果是
r=1.000000 g=1.000000 b=0.000000 a=1.000000, 正如预期的那样。
[UIColor redColor]
给出 r=1.000000 g=0.000000 b=0.000000 a=1.000000, 再次如预期。 对于blueColor
和greenColor
也是如此。
但是,[UIColor blackColor]
和[UIColor WhiteColor]
的结果似乎完全异常,我不知道我在做什么错了(如果我确实是错的话)。
也就是说,[UIColor blackColor]
给出 r=0.000000 g=1.000000 b=0.000000 a=0.000000, 这是透明的绿色,
[UIColor WhiteColor]
给出 r=1.000000 g=1.000000 b=0.000000 a=0.000000, 这是透明的黄色。
如果有人可以:
(1)解释我做错了什么
(2) 复制我的异常结果并告诉我这不是我,或者
(3)用大锤子敲我的头,这样就不那么疼了。
霍华德
I'm trying to extract the rgb components of a UIColor
in order to hand-build the pixels in a CGBitmapContext
. The following sample code works fine for most of the UIColor
constants but, confusingly, not all. To wit:
CGColorRef color = [[UIColor yellowColor] CGColor];
const float* rgba = CGColorGetComponents(color);
float r = rgba[0];
float g = rgba[1];
float b = rgba[2];
float a = rgba[3];
NSLog( @"r=%f g=%f b=%f a=%f", r, g, b, a);
The results for [UIColor yellowColor]
above are
r=1.000000 g=1.000000 b=0.000000 a=1.000000,
as expected.
[UIColor redColor]
gives
r=1.000000 g=0.000000 b=0.000000 a=1.000000,
again as expected. Similarly for blueColor
and greenColor
.
However, the results for [UIColor blackColor]
and [UIColor whiteColor]
seem completely anomalous, and I don't know what I'm doing wrong (if indeed I am).
To wit, [UIColor blackColor]
gives
r=0.000000 g=1.000000 b=0.000000 a=0.000000,
which is a tranparent green,
and [UIColor whiteColor]
gives
r=1.000000 g=1.000000 b=0.000000 a=0.000000,
which is a transparent yellow.
I'd appreciate it if somebody could either:
(1) explain what I'm doing wrong
(2) replicate my anomalous results and tell me it's not me, or
(3) hit me over the head with a big hammer so it stops hurting so much.
Howard
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您假设颜色空间始终为 RGBA,但事实并非如此。
试试这个代码:
模型将产生
kCGColorSpaceModelMonochrome
。You are assuming the color space is always RGBA, which is not the case.
Try this code:
And model will yield
kCGColorSpaceModelMonochrome
.我认为您缺少的是颜色可以在不同的颜色空间中定义:您假设它们都是 RGBA。
例如, 文档指出
blackColor
“返回灰度值为0.0且alpha值为1.0的颜色对象”。 所以我认为只有两个分量对黑色有效,而不是四个。I think the thing you're missing is that colors can be defined in different color spaces: you're assuming they're all RGBA.
For instance, the docs state that
blackColor
"Returns a color object whose grayscale value is 0.0 and whose alpha value is 1.0". So I think only two components are valid for black, not four.