我正在尝试创建一个从绿色到红色的自定义UIColor取决于百分比值,但我不知道我该怎么做呢?
有什么想法吗?
答案 0 :(得分:3)
如果你只是想要一个线性混合,那么这些方面的东西应该有用:
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),虽然 - 一种丑陋的橙色 - 所以你可能想要这样做,这只会调整红色和绿色之间的色调,通过黄色,和让你根据自己的喜好改变饱和度/亮度:
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。
答案 1 :(得分:1)
我一直在寻找这样的东西,所以我自己写了。但是我很快就新来了
static func successColor(percent: Int) -> UIColor {
let p = CGFloat(percent)
let tempR = (100.0-p)/100
let r: CGFloat = tempR < 0 ? 0 : tempR
let tempG = 1+(p-100.0)/100.0
let g: CGFloat = tempG < 0 ? 0 : tempG
return UIColor(red: r, green: g, blue: 0, alpha: 1)
}
答案 2 :(得分:1)
您可以使用我的扩展程序从颜色数组中按百分比获取中间颜色
extension Array where Element: UIColor {
func intermediate(percentage: CGFloat) -> UIColor {
let percentage = Swift.max(Swift.min(percentage, 100), 0) / 100
switch percentage {
case 0: return first ?? .clear
case 1: return last ?? .clear
default:
let approxIndex = percentage / (1 / CGFloat(count - 1))
let firstIndex = Int(approxIndex.rounded(.down))
let secondIndex = Int(approxIndex.rounded(.up))
let fallbackIndex = Int(approxIndex.rounded())
let firstColor = self[firstIndex]
let secondColor = self[secondIndex]
let fallbackColor = self[fallbackIndex]
var (r1, g1, b1, a1): (CGFloat, CGFloat, CGFloat, CGFloat) = (0, 0, 0, 0)
var (r2, g2, b2, a2): (CGFloat, CGFloat, CGFloat, CGFloat) = (0, 0, 0, 0)
guard firstColor.getRed(&r1, green: &g1, blue: &b1, alpha: &a1) else { return fallbackColor }
guard secondColor.getRed(&r2, green: &g2, blue: &b2, alpha: &a2) else { return fallbackColor }
let intermediatePercentage = approxIndex - CGFloat(firstIndex)
return UIColor(red: CGFloat(r1 + (r2 - r1) * intermediatePercentage),
green: CGFloat(g1 + (g2 - g1) * intermediatePercentage),
blue: CGFloat(b1 + (b2 - b1) * intermediatePercentage),
alpha: CGFloat(a1 + (a2 - a1) * intermediatePercentage))
}
}
}
用法:
let color = [.green, .red].intermediate(percentage: 50)
更多颜色:
let color = [.green, .yellow, .red].intermediate(percentage: 70)