ある UIColor から別の UIColor に徐々に色を変化させる
環境: Swift 4.2.1
ある UIColor から別の UIColor に徐々に色を変化させるヘルパーメソッド。
extension UIColor { static func colorLerp(from: UIColor, to: UIColor, progress: CGFloat) -> UIColor { let t = max(0, min(1, progress)) var redA: CGFloat = 0 var greenA: CGFloat = 0 var blueA: CGFloat = 0 var alphaA: CGFloat = 0 from.getRed(&redA, green: &greenA, blue: &blueA, alpha: &alphaA) var redB: CGFloat = 0 var greenB: CGFloat = 0 var blueB: CGFloat = 0 var alphaB: CGFloat = 0 to.getRed(&redB, green: &greenB, blue: &blueB, alpha: &alphaB) let lerp = { (a: CGFloat, b: CGFloat, t: CGFloat) -> CGFloat in return a + (b - a) * t } let r = lerp(redA, redB, t) let g = lerp(greenA, greenB, t) let b = lerp(blueA, blueB, t) let a = lerp(alphaA, alphaB, t) return UIColor(red: r, green: g, blue: b, alpha: a) } }
progress を徐々に変化させることで色が変化していく。
let color = UIColor.colorLerp(from: .white, to: .black, progress: 0.3)