如何访问UIColor的RGB值?

4

我有一个iOS绘图应用程序,其中有按钮让用户选择要绘制的颜色。由于我的画笔使用RGB值,但我的颜色常量是UIColors,所以需要进行转换。我尝试过

private var currentButton: UIButton? {
    willSet{
        currentButton?.layer.borderWidth = 0
    }
    didSet{
        currentButton?.layer.borderWidth = 2
        let index = (currentButton?.tag)! - 1
        drawView.brush.blue = colors[index].ciColor.blue //Here is where I get the error
        drawView.brush.green = colors[index].ciColor.green
        drawView.brush.red = colors[index].ciColor.red
    }
}

我在另一个StackOverflow问题中找到了这个代码。然而,在第8行尝试获取RGB值时,我遇到了这个错误:
Terminating app due to uncaught exception 
'NSInvalidArgumentException', reason: '*** -CIColor not defined for the UIColor UIExtendedSRGBColorSpace 1 1 1 1; need to first convert colorspace.'

显然我需要转换颜色空间。但是CIColor.colorSpace只能获取,不能设置。我做错了什么?


var ciColor: CIColor { get } Description The Core Image color associated with the receiver. This property throws an exception if the color object was not initialized with a Core Image color. - Leo Dabus
1
你可以使用CoreImage.CIColor初始化器从你的UIColor中创建一个新的颜色,例如CoreImage.CIColor(color: colors[index]).blue,它的优点是不会返回可选值。 - Leo Dabus
1个回答

7
使用getRed(_:green:blue:alpha:)方法:
var red:   CGFloat = 0
var green: CGFloat = 0
var blue:  CGFloat = 0
var alpha: CGFloat = 0

color.getRed(&red, green: &green, blue: &blue, alpha: &alpha)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接