有没有一种方法可以生成一个UIColor
到UIColor
范围内的red
表(或者说green
的数组),使得变量{{1 }}将具有相应的颜色var match = 100
,而green
将具有相应的颜色var match = 0
,并且中间变量值接近red
时,它们之间的变量值将变得更绿色?>
感谢您的帮助。
答案 0 :(得分:1)
这是一个有用的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)