Search code examples
swiftgradientuicolorcifilter

CIFilter CISmoothLinearGradient crashing when passing color in Swift


I'm trying to use the CISmoothLinearGradient in an iOS app, and it seems to not like the 2nd inputColor no matter what I put in, possibly because of the alpha parameter.

I've tried several other ways of setting up the CIFilter, but I used this to pinpoint where the issue was cropping up:

    let gradientFilter = CIFilter(name: "CISmoothLinearGradient")
    gradientFilter?.setDefaults()
    gradientFilter?.setValue([0, 0], forKey: "inputPoint0")
    gradientFilter?.setValue(inputPoint1Vector, forKey: "inputPoint1")
    gradientFilter?.setValue(UIColor.black, forKey: "inputColor0")
    gradientFilter?.setValue(UIColor(red: 1, green: 1, blue: 1, alpha: 1), forKey: "inputColor1") // crash

The console states: -[UICachedDeviceWhiteColor alpha]: unrecognized selector sent to instance 0x1c4259830

Originally I was using UIColor.white, but still it shows that UICachedDeviceWhiteColor error.


Solution

  • CIColor and CIVector will do the work in this case.

    Replace the values of RGB and x,y according to your need

            var color1 = CIColor(red: 238/255, green: 97/255, blue: 35/255, alpha: 1)
            var color2 = CIColor(red: 246/255, green: 66/255, blue: 227/255, alpha: 1)
    
            let gradientFilter = CIFilter(name: "CISmoothLinearGradient")
            gradientFilter?.setDefaults()
            gradientFilter?.setValue(CIVector(x: 0, y: 0), forKey: "inputPoint0")
            gradientFilter?.setValue(CIVector(x: 200, y: 200), forKey: "inputPoint1")
            gradientFilter?.setValue(color1, forKey: "inputColor0")
            gradientFilter?.setValue(color2, forKey: "inputColor1")