Вот полезное расширение UIColor
, которое позволяет смешивать два цвета в процентах.
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)
}
}
Примеры:
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)