小编典典

从UIColor提取RGB值

swift

我已经看到人们在Objective-
C中做到这一点,但是我很快就遇到了麻烦。我已经从图片中获得了像素的颜色,但是现在我需要分别获取红色,绿色和蓝色的值。这是我所拥有的(h,w和rgb是整数,image.getPixelColor(CGPoint)返回UIColor):

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

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


阅读 500

收藏
2020-07-07

共1个答案

小编典典

您可以将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
}
2020-07-07