2012-02-21 76 views
1

下面是获取RGB颜色组件的代码片段。如果_countComponents少于四个,例如两个,我该怎么办?我试图让颜色灰色的成分[的UIColor grayColor]在objective-c中获取颜色成分

int _countComponents = CGColorGetNumberOfComponents(colorRef); 

if (_countComponents == 4) { 
    const CGFloat *_components = CGColorGetComponents(colorRef); 
    CGFloat red  = _components[0]; 
    CGFloat green = _components[1]; 
    CGFloat blue = _components[2]; 
    CGFloat alpha = _components[3]; 
+0

你说的意思是:* “我试图让灰色的成分[的UIColor grayColor]” *? – sch 2012-02-21 19:42:54

回答

1

彩色的组分取决于相关联color space

所以_components[0]_components[1]等不是必需的红色,绿色的蓝色和alpha。

+0

链接的颜色空间帮助我感谢你 – Laszlo 2012-03-11 15:03:20

5

如果你有一个UIColor的实例,你想要它的RGB值,为什么不使用-getRed:green:blue:alpha:方法?

CGFloat r, g, b, a; 
BOOL success = [myColor getRed:&r green:&g blue:&b alpha:&a]; 
if (success) { 
    // the color was converted to RGB successfully, go ahead and use r,g,b, and a. 
} 
1

新建答案

重新阅读的问题后。要回答这个灰色成分的问题,您阅读的方式是通过 - (BOOL)getWhite:阿尔法:

所以,你会怎么办按照凯莱布的东西,如:

BOOL success = [myColor getWhite:&w alpha:&a]; 

这给你的灰度值w为0至1和α值a为0到1

看到苹果文档getWhite:alpha:

老答案

从这个SO质疑how-to-access-the-color-components-of-an-uicolor

见(而旧)ArsTechnica ARTICAL iphone-development-accessing-uicolor-components

+0

+1停止阅读问题 - 你让我们其他人看起来很傻。 – Caleb 2012-02-21 20:23:57

+0

@Caleb令人惊讶的是,阅读会为你做什么..大声笑 – 2012-02-21 20:32:44