问题描述
我试图从绿色到红色创建自定义UIColor取决于百分比值,但是我不知道该怎么做?
i am trying to create a custom UIColor from Green to Red depends on a Percentage Value, but i have no idea how can i do something like that?
有什么想法吗?
推荐答案
如果您只想进行线性混合,则应遵循以下几条规则:
Something along these lines should work, if you just want a linear mix:
func mixGreenAndRed(greenAmount: Float) -> UIColor {
return UIColor(red: (1.0 - greenAmount), green: greenAmount, blue: 0.0, alpha: 1.0)
}
尽管那会通过RGB(0.5、0.5、0)进行混合(一种丑陋的橙色),所以您可能要这样做,它只会在红色和绿色之间进行调整,通过黄色进行调整,然后让您根据自己的喜好更改饱和度/亮度:
That one will blend through RGB (0.5, 0.5, 0), though—a kind of ugly orange—so you might want to do this instead, which will just adjust the hue between red and green, passing through yellow, and let you alter saturation / brightness to your taste:
func mixGreenAndRed(greenAmount: Float) -> UIColor {
// the hues between red and green go from 0…1/3, so we can just divide percentageGreen by 3 to mix between them
return UIColor(hue: greenAmount / 3, saturation: 1.0, brightness: 1.0, alpha: 1.0)
}
在两种情况下, greenAmount
的值都应在0.0–1.0之间,而不是0–100.
In both cases greenAmount
should be a value between 0.0–1.0, not 0–100.
这篇关于颜色从绿色变为红色(按百分比)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!