Skip to content

Instantly share code, notes, and snippets.

@thillsman
Created November 5, 2016 19:37
Show Gist options
  • Save thillsman/f8a8ab57a0ab6568a1debf350a85dc62 to your computer and use it in GitHub Desktop.
Save thillsman/f8a8ab57a0ab6568a1debf350a85dc62 to your computer and use it in GitHub Desktop.
Morph from one UIColor to another
extension UIColor {
// First extend UIColor to make it easier to get components out
var coreImageColor: CIColor {
return CIColor(color: self)
}
var components: (red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) {
let color = coreImageColor
return (color.red, color.green, color.blue, color.alpha)
}
// Class method version
static func morphColor(from first: UIColor, to second: UIColor, progress: CGFloat) -> UIColor {
func morphComponent(from firstValue: CGFloat, to secondValue: CGFloat) -> CGFloat {
let diff = secondValue - firstValue
return diff * progress + firstValue
}
let newRed = morphComponent(from: first.components.red, to: second.components.red)
let newGreen = morphComponent(from: first.components.green, to: second.components.green)
let newBlue = morphComponent(from: first.components.blue, to: second.components.blue)
let newAlpha = morphComponent(from: first.components.alpha, to: second.components.alpha)
return UIColor(red: newRed, green: newGreen, blue: newBlue, alpha: newAlpha)
}
// Instance method version
func morph(to second: UIColor, progress: CGFloat) -> UIColor {
return UIColor.morphColor(from: self, to: second, progress: progress)
}
}
// Usage - set up your beginning and ending colors, then morph!
let color1 = UIColor(red: 1.0, green: 0.0, blue: 0.0, alpha: 0.5)
let color2 = UIColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
let newColor = UIColor.morphColor(from:color1, to:color2, progress: 0.5)
let alternativeNewColor = color1.morph(to: color2, progress: 0.5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment