Search code examples
iosswiftuicolorcolor-space

CIColor to UIColor -> CIColor not defined for the UIColor UIExtendedSRGBColorSpace


I'm trying to implement CIColor from rgb-hex colorspace as follows:

    let bottomColor = UIColor.init(red: 235/255, green: 250/255, blue: 255/255, alpha: 1.0).ciColor

However, I keep on hitting the following error:

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

I'm not sure what this means. How to fix this?


Solution

  • this will work:

    let uiColor = UIColor.init(red: 235.0/255.0, green: 250.0/255.0, blue: 255.0/255.0, alpha: 1.0)
    let bottomColor = CIColor(color: uiColor)
    

    You can also add an extension on UIColor:

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

    And then call it via:

    let bottomColor = UIColor.init(red: 235.0/255.0, green: 250.0/255.0, blue: 255.0/255.0, alpha: 1.0).coreImageColor
    

    The answer and explanation for which I found in this related question.