从UIColor中提取RGB值

时间:2015-02-15 23:39:51

标签: ios swift swift3 rgb uicolor

我见过人们在objective-c中这样做,但我很快就遇到了麻烦。我从图片中获得了一个像素的颜色,但现在我需要采用单独的红色,绿色和蓝色值。这是我所拥有的(h,w和rgb是整数,image.getPixelColor(CGPoint)返回一个UIColor):

 xArry[h][w][rgb] = image.getPixelColor(CGPoint(x: w, y: h))

如何将此UIColor更改为红色,绿色和蓝色值?谢谢!

4 个答案:

答案 0 :(得分:48)

您可以将UIColor转换为CIColor,然后从中提取颜色成分,如下所示:

更新: Xcode 8.3.2•Swift 3.1

extension UIColor {
    var coreImageColor: CIColor {
        return CIColor(color: self)
    }
    var components: (red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) {
        let coreImageColor = self.coreImageColor
        return (coreImageColor.red, coreImageColor.green, coreImageColor.blue, coreImageColor.alpha)
    }
}

用法:

let myColor = UIColor(red: 0.5, green: 1, blue: 0.25, alpha: 0.5)
let myCIColor = myColor.coreImageColor
let greencomponent = myColor.components.green
let myColorComponents = myColor.components
print(myColorComponents.red)   // 0.5
print(myColorComponents.green) // 1.0
print(myColorComponents.blue)  // 0.25
print(myColorComponents.alpha) // 0.5


你也可以使用函数getRed()并创建一个扩展来提取组件,如下所示,但结果是可选的:

extension UIColor {
    var components: (red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat)? {
        var r: CGFloat = 0, g: CGFloat = 0, b: CGFloat = 0, a: CGFloat = 0
        return getRed(&r, green: &g, blue: &b, alpha: &a) ? (r,g,b,a) : nil
    }
}

用法

let myColor = UIColor(red: 0.5, green: 1, blue: 0.25, alpha: 0.5)
if let myColorComponents = myColor.components {
    print(myColorComponents.red)   // 0.5
    print(myColorComponents.green) // 1.0
    print(myColorComponents.blue)  // 0.25
    print(myColorComponents.alpha) // 0.5
}

答案 1 :(得分:16)

对于UIColor,你可以使用getRed方法:

let yourColor = UIColor(red: 0/255, green: 184/255, blue: 48/255, alpha: 1.0)
var r: CGFloat = 0, g: CGFloat = 0, b: CGFloat = 0, a: CGFloat = 0
yourColor.getRed(&r, green: &g, blue: &b, alpha: &a)
print("red: \(r), green: \(g), blue: \(b)")

答案 2 :(得分:4)

您可以使用CGColorGetComponents获取CGColor的颜色数组(未在swift3中测试)

const CGFloat *_components = CGColorGetComponents(yourUIColor.CGColor);
    CGFloat red     = _components[0];
    CGFloat green = _components[1];
    CGFloat blue   = _components[2];
    CGFloat alpha = _components[3];

您还可以使用

找到该颜色的颜色成分数
CGColorGetNumberOfComponents

您必须在获取值之前验证组件数量。灰色有2个成分(灰色和alpha),rgb颜色有4个成分:R,G,B,A

https://developer.apple.com/library/ios/documentation/GraphicsImaging/Reference/CGColor/index.html#//apple_ref/c/func/CGColorGetNumberOfComponents

答案 3 :(得分:1)

未经测试但这应该有效。刚发现它:

   xArry[h][w][rgb] = Int(image.getPixelColor(CGPoint(x: w, y: h)).CIColor.red())