问题
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?
Any ideas?
回答1:
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)
}
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)
}
In both cases greenAmount
should be a value between 0.0–1.0, not 0–100.
回答2:
You can use my extension to get the intermediate color from an array of colors by percentage
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))
}
}
}
Usage:
let color = [.green, .red].intermediate(percentage: 50)
and more colors:
let color = [.green, .yellow, .red].intermediate(percentage: 70)
回答3:
I was looking for something like this, so I wrote it myself. But I'm very new in swift
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)
}
来源:https://stackoverflow.com/questions/25943241/color-from-green-to-red-with-percentage