Search code examples
iosswiftgradientuicolor

iOS (Swift): representing scaled value as UIColor


Is there a way to generate a UIColor table (or an array of UIColors, say) ranging from red to green such that a variable var match = 100 would have a corresponding colour green whilst a var match = 0 would have a corresponding colour red and variable values in-between would become greener as their value approaches 100?

Thanks for any help.


Solution

  • Here's a helpful UIColor extension that lets you get a blend between two colors based on a percentage.

    extension UIColor {
        // This function calculates a new color by blending the two colors.
        // A percent of 0.0 gives the "self" color
        // A percent of 1.0 gives the "to" color
        // Any other percent gives an appropriate color in between the two
        func blend(to: UIColor, percent: Double) -> UIColor {
            var fR : CGFloat = 0.0
            var fG : CGFloat = 0.0
            var fB : CGFloat = 0.0
            var tR : CGFloat = 0.0
            var tG : CGFloat = 0.0
            var tB : CGFloat = 0.0
    
            getRed(&fR, green: &fG, blue: &fB, alpha: nil)
            to.getRed(&tR, green: &tG, blue: &tB, alpha: nil)
    
            let dR = tR - fR
            let dG = tG - fG
            let dB = tB - fB
    
            let perc = min(1.0, max(0.0, percent))
            let rR = fR + dR * CGFloat(perc)
            let rG = fG + dG * CGFloat(perc)
            let rB = fB + dB * CGFloat(perc)
    
            return UIColor(red: rR, green: rG, blue: rB, alpha: 1.0)
        }
    }
    

    Examples:

    let red = UIColor.red.blend(to: .green, percent: 0)
    let mix = UIColor.red.blend(to: .green, percent: 0.5)
    let green = UIColor.red.blend(to: .green, percent: 1)