'blendedColorWithFraction:ofColor:' in iOS

2019-08-11 17:47发布

问题:

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])!

回答1:

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);
    }
}


回答2:

Try exporting StyleKit class, not just the canvas method snippet. StyleKit includes extension of UIColor which implements this method.