Search code examples
iospaintcode

'blendedColorWithFraction:ofColor:' in iOS Swift and ObjC


I've got a simple gradient: 2 colors, 1 location. But it's spitting out code that can't work on UIColors:

let gradient = CGGradientCreateWithColors(CGColorSpaceCreateDeviceRGB(), [gradientColor2.CGColor, gradientColor2.blendedColorWithFraction(0.5, ofColor: gradientColor).CGColor, gradientColor.CGColor], [0.14, 0.5, 1])!

Solution

  • Here is the method implementation if you don't want to use StyleKit:

    extension UIColor {
        func blendedColorWithFraction(fraction: CGFloat, ofColor color: UIColor) -> UIColor {
            var r1: CGFloat = 1.0, g1: CGFloat = 1.0, b1: CGFloat = 1.0, a1: CGFloat = 1.0
            var r2: CGFloat = 1.0, g2: CGFloat = 1.0, b2: CGFloat = 1.0, a2: CGFloat = 1.0
    
            self.getRed(&r1, green: &g1, blue: &b1, alpha: &a1)
            color.getRed(&r2, green: &g2, blue: &b2, alpha: &a2)
    
            return UIColor(red: r1 * (1 - fraction) + r2 * fraction,
                green: g1 * (1 - fraction) + g2 * fraction,
                blue: b1 * (1 - fraction) + b2 * fraction,
                alpha: a1 * (1 - fraction) + a2 * fraction);
        }
    }