A Tyshka A Tyshka - 1 month ago 51x
Swift Question

How can I access the RGB values of a UIColor?

I have an iOS drawing app with buttons that let a user choose colors to draw with. Since my brush uses RGB values but my color constants are UIColors, I need to convert. I tried

private var currentButton: UIButton? {
currentButton?.layer.borderWidth = 0
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

Which I found in another StackOverflow question. However, when I try to get an RGB value in line 8 I get this error:

Terminating app due to uncaught exception
'NSInvalidArgumentException', reason: '*** -CIColor not defined for the UIColor UIExtendedSRGBColorSpace 1 1 1 1; need to first convert colorspace.'

It clearly says that I need to convert color space. But
is get-only. What am I doing wrong?

Rob Rob

Use 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)