Assuming values are normalized from 0 to 1, what is the algoritm to get a color to create a heatmap like this?
1 is red, .5 is green, 0 is dark blue.
Working in
I leave here a Swift 4 implementation based on this blog post for any amount of colors! Perfect explanation is there! Hope it helps and saves some time to someone!
import Foundation
import UIKit
struct ColorPoint {
let color: UIColor
let value: CGFloat
}
class HeatMapColor {
var colorPoints: [ColorPoint]
init(colorPoints: [ColorPoint]) {
self.colorPoints = colorPoints
}
func colorAt(value: CGFloat) -> UIColor {
if(colorPoints.isEmpty) { return UIColor.black }
let colorsPointsToUse = colorPoints.sorted { (colorPointA, colorPointB) -> Bool in
return colorPointA.value <= colorPointB.value
}
for (index, colorPoint) in colorsPointsToUse.enumerated() where value < colorPoint.value {
let previousColorPoint = colorsPointsToUse[max(0, index - 1)]
let valueDiff = previousColorPoint.value - colorPoint.value
let fraction = valueDiff == 0 ? 0 : (value - colorPoint.value) / valueDiff
guard
let prevComp = previousColorPoint.color.cgColor.components,
let currComp = colorPoint.color.cgColor.components else { continue }
let red = (prevComp[0] - currComp[0]) * fraction + currComp[0]
let green = (prevComp[1] - currComp[1]) * fraction + currComp[1]
let blue = (prevComp[2] - currComp[2]) * fraction + currComp[2]
return UIColor(red: red, green: green, blue: blue, alpha: 1.0)
}
return colorsPointsToUse.last!.color
}
}