Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Return a color based on percentage. 0% is Red, and 100% is Green
extension UIColor {
static func colorForPercent(_ percentage: Double) -> UIColor {
switch percentage {
case 0...0.5:
return firstHalf(percentage: percentage * 2)
case 0.5...1:
return secondHalf(percentage: (percentage - 0.5) * 2)
default:
fatalError("Bad Input: percentage must satisfy 0 <= percentage <= 1")
}
}
static fileprivate func firstHalf(percentage: Double) -> UIColor {
let begin = UIColor.systemGreen.cgColor.components!
let end = UIColor.systemYellow.cgColor.components!
return createColor(begin: begin, end: end, percentage: percentage)
}
static fileprivate func secondHalf(percentage: Double) -> UIColor {
let begin = UIColor.systemYellow.cgColor.components!
let end = UIColor.systemRed.cgColor.components!
return createColor(begin: begin, end: end, percentage: percentage)
}
static fileprivate func createColor(begin: [CGFloat], end: [CGFloat], percentage: Double) -> UIColor {
var colorDiff = begin
for i in 0 ..< 3 {
colorDiff[i] = begin[i] + (end[i] - begin[i]) * CGFloat(percentage)
}
return UIColor(red: colorDiff[0], green: colorDiff[1], blue: colorDiff[2], alpha: 1)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.