4

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? {
    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
    }
}

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 CIColor.colorSpace is get-only. What am I doing wrong?

A Tyshka
  • 3,830
  • 7
  • 24
  • 46
  • `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 Sep 05 '16 at 20:56
  • 1
    You can use CoreImage.CIColor initializer to create a new color from your UIColor `CoreImage.CIColor(color: colors[index]).blue` with the advantage that it doesn't return an optional. – Leo Dabus Sep 05 '16 at 21:03

1 Answers1

7

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)
Rob
  • 415,655
  • 72
  • 787
  • 1,044