之前看过这个问题,但我的例子似乎没有用。
const CGFloat *toCol = CGColorGetComponents([[UIColor greenColor] CGColor]);
使用GDB查看数组是空的。任何提示?
答案 0 :(得分:109)
您提供的代码示例应该有效。
试试这个:
UIColor uicolor = [[UIColor greenColor] retain];
CGColorRef color = [uicolor CGColor];
int numComponents = CGColorGetNumberOfComponents(color);
if (numComponents == 4)
{
const CGFloat *components = CGColorGetComponents(color);
CGFloat red = components[0];
CGFloat green = components[1];
CGFloat blue = components[2];
CGFloat alpha = components[3];
}
[uicolor release];
答案 1 :(得分:38)
在iOS 5中,您可以使用:
UIColor *color = [UIColor orangeColor];
CGFloat red = 0.0, green = 0.0, blue = 0.0, alpha = 0.0;
if ([color respondsToSelector:@selector(getRed:green:blue:alpha:)]) {
[color getRed:&red green:&green blue:&blue alpha:&alpha];
} else {
const CGFloat *components = CGColorGetComponents(color.CGColor);
red = components[0];
green = components[1];
blue = components[2];
alpha = components[3];
}
答案 2 :(得分:14)
这是一个全面的解决方案,也考虑了非RGB颜色,例如[UIColor blackColor]
UIColor *color = [UIColor blackColor];
CGFloat red = 0.0, green = 0.0, blue = 0.0, alpha = 0.0;
// iOS 5
if ([color respondsToSelector:@selector(getRed:green:blue:alpha:)]) {
[color getRed:&red green:&green blue:&blue alpha:&alpha];
} else {
// < iOS 5
const CGFloat *components = CGColorGetComponents(color.CGColor);
red = components[0];
green = components[1];
blue = components[2];
alpha = components[3];
}
// This is a non-RGB color
if(CGColorGetNumberOfComponents(color.CGColor) == 2) {
CGFloat hue;
CGFloat saturation;
CGFloat brightness;
[color getHue:&hue saturation:&saturation brightness:&brightness alpha:&alpha];
}
答案 3 :(得分:7)
只需使用memcpy:
CGColorRef tmpColor = [[currentColorView backgroundColor] CGColor];
CGFloat newComponents[4] = {};
memcpy(newComponents, CGColorGetComponents(tmpColor), sizeof(newComponents));
// now newComponents is filled with tmpColor rgba data
答案 4 :(得分:5)
感谢威尔斯特的指示。对于任何使用灰度颜色的人(使用colorWithWhite:alpha:
创建),下面的代码示例将让您计算出白色值(HSV方法不适用于以这种方式创建的颜色)。
CGFloat red = 0.0, green = 0.0, blue = 0.0, alpha = 0.0, white = 0.0;
// This is a non-RGB color
if(CGColorGetNumberOfComponents(self.color.CGColor) == 2) {
[self.color getWhite:&white alpha:&alpha];
}
else {
// iOS 5
if ([self.color respondsToSelector:@selector(getRed:green:blue:alpha:)]) {
[self.color getRed:&red green:&green blue:&blue alpha:&alpha];
} else {
// < iOS 5
const CGFloat *components = CGColorGetComponents(self.color.CGColor);
red = components[0];
green = components[1];
blue = components[2];
alpha = components[3];
}
}
答案 5 :(得分:1)
本文帮助我解决了这个问题,或者至少构建了解决它的框架。
http://developer.apple.com/iphone/library/qa/qa2007/qa1509.html
答案 6 :(得分:1)
这里有一些更直接的示例代码,用于从任意颜色中获取RGB组件:
答案 7 :(得分:1)
结帐uicolor-utilities。看起来像是一个非常好的库,用于执行此操作以及UIColor的许多其他有用的东西。例如,使用此库,您可以编写:
CGFloat red = [myColor red];