7

是否有更快(或更好)的方法从 UIColor 获取 [RGBA] 颜色分量?周围似乎有很多变化(有些在这里,基本上都与我在这里所做的相似)我只是好奇是否有替代方案,因为它似乎有点“缺乏”,因为其他一切通常都是如此完整且经过深思熟虑。

if([eachKey isEqualToString:@"NSColor"]) {
    UIColor *newColor = [attrs valueForKey:eachKey];
    //NSLog(@"COLOR: %@", newColor);
    CGColorRef colorRef = [newColor CGColor];
    //NSLog(@"%@", colorRef);
    int numComponets = CGColorGetNumberOfComponents(colorRef);
    if(numComponets == 4) {
        const CGFloat *components = CGColorGetComponents(colorRef);
        CGFloat compR = components[0];
        CGFloat compG = components[1];
        CGFloat compB = components[2];
        CGFloat compA = components[3];

        //NSLog(@"R:%f G:%f B:%f, A:%f", compR, compG, compB, compA);
    }
}

我不是在寻找如何(我想我有上面的长版本)我只是想知道这是否是你现在应该这样做的方式?

4

3 回答 3

16
CGFloat r, g, b, a;    
[MyColor getRed: &r green:&g blue:&b alpha:&a];

需要 iOS 5+。

于 2012-06-28T16:23:17.143 回答
2

在类参考中检查此方法。

于 2012-06-28T16:23:54.783 回答
1
- (BOOL)getRed:(CGFloat *)red 
         green:(CGFloat *)green 
          blue:(CGFloat *)blue 
         alpha:(CGFloat *)alpha

上面的方法不可靠,它会返回 NO [UIColor whiteColor](或其他灰度color)。

利用

if(numComponets == 5) {

代替

if(numComponets == 4) {

来自 api 文档:

The size of the array is one more than the number of components of the color 
space for the color.
于 2012-11-23T17:37:05.273 回答