UIColor - getRed:... - 引发异常

时间:2011-11-06 09:32:01

标签: ios ios4

我有以下测试代码:

CGFloat endRed, endGreen, endBlue, endAlpha;

[[UIColor greenColor] getRed:&endRed green:&endGreen blue:&endBlue alpha:&endAlpha];

我在一个UIView类的drawRect方法中调用。 此代码失败,异常

2011-11-06 02:29:28.671 Chartous[13457:b303] -[UICachedDeviceRGBColor getRed:green:blue:alpha:]: unrecognized selector sent to instance 0x4e7ea10
2011-11-06 02:29:28.673 Chartous[13457:b303] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UICachedDeviceRGBColor getRed:green:blue:alpha:]: unrecognized selector sent to instance 0x4e7ea10'

这里有什么问题?

3 个答案:

答案 0 :(得分:27)

尝试另一种方法:

const CGFloat* components = CGColorGetComponents([[UIColor greenColor] CGColor]);
CGFloat red = components[0];
CGFloat green = components[1];
CGFloat blue = components[2];
CGFloat alpha = CGColorGetAlpha([[UIColor greenColor] CGColor]);

答案 1 :(得分:4)

此方法仅适用于ios5及更高版本。您是在模拟器或设备上的早期iOS版本上运行它吗?我假设你的问题上有标签。

答案 2 :(得分:3)

在单调颜色的情况下,组件数量为2,因此您需要另外检查

E.g。 [UIColor whitecolor]只有2个alpha和颜色组件

size_t num = CGColorGetNumberOfComponents(cgPrevColor);
CGFloat r,g,b;
if(num==2) {
    r = g = b = components[0];
} else {
    r = components[0];
    g = components[1];
    b = components[2];            
}