Here's a Swift 3 version that uses a convenience initializer and adds a function to return an array of intermediate colors.
extension UIColor {
convenience init?(interpolatedFrom fromColor: UIColor, to toColor: UIColor, byFraction fraction: CGFloat) {
guard fromColor.cgColor.numberOfComponents >= 4 && toColor.cgColor.numberOfComponents >= 3 else {
print("Color interpolation requires both the to and from color to be provided with components for red, green, blue, and alpha.")
return nil
}
var fraction = max(0, fraction)
fraction = min(1, fraction)
guard let fromComponents = fromColor.cgColor.components, let toComponents = toColor.cgColor.components else {
print("Unable to extract components from colors provided for interpolation.")
return nil
}
let red: CGFloat = CGFloat(fromComponents[0] + (toComponents[0] - fromComponents[0]) * fraction)
let green: CGFloat = CGFloat(fromComponents[1] + (toComponents[1] - fromComponents[1]) * fraction)
let blue: CGFloat = CGFloat(fromComponents[2] + (toComponents[2] - fromComponents[2]) * fraction)
let alpha: CGFloat = CGFloat(fromComponents[3] + (toComponents[3] - fromComponents[3]) * fraction)
self.init(red:red, green:green, blue:blue, alpha:alpha)
}
class func interpolateColors(from fromColor: UIColor, to toColor: UIColor, interpolations: Int) -> [UIColor] {
guard interpolations > 2 else { return [fromColor, toColor] }
let increment = CGFloat(1) / CGFloat(interpolations - 1)
var result = [UIColor]()
for i in 0..<interpolations {
let fraction = CGFloat(i) * increment
guard let color = UIColor(interpolatedFrom: fromColor, to: toColor, byFraction: fraction) else {
print("Unable to create an interpolated color for fraction \(fraction). Will use gray instead.")
result.append(.gray)
continue
}
result.append(color)
}
return result
}
}
Usage:
let color1 = UIColor(red: 0.137, green: 0.157, blue: 0.196, alpha: 1)
let color2 = UIColor(red: 0.455, green: 0.475, blue: 0.525, alpha: 1)
let interpolatedColors = UIColor.interpolateColors(from: color1, to: color2, interpolations: 5)
Output:
[
r 0.137 g 0.157 b 0.196 a 1.0,
r 0.216 g 0.236 b 0.278 a 1.0,
r 0.296 g 0.316 b 0.361 a 1.0,
r 0.375 g 0.396 b 0.443 a 1.0,
r 0.455 g 0.475 b 0.525 a 1.0
]