Skip to content

Instantly share code, notes, and snippets.

@ha1f
Last active Nov 24, 2020
Embed
What would you like to do?
//
// UIKit+lerp.swift
// ha1f
//
extension CGRect {
/// 線形補間した中間矩形を返す
/// - parameter otherRect: 目指す先の矩形
/// - parameter rate: 0-1の間の値。0なら自分と、1ならotherRectと同じ。
func lerp(_ otherRect: CGRect, rate: CGFloat) -> CGRect {
let lerp = _lerpCurried(rate)
return CGRect(
x: lerp(origin.x, otherRect.origin.x),
y: lerp(origin.y, otherRect.origin.y),
width: lerp(width, otherRect.width),
height: lerp(height, otherRect.height)
)
}
}
extension UIColor {
/// 線形補間した中間色を返す
/// - parameter otherColor: 目指す先の色
/// - parameter rate: 0-1の間の値。0なら自分と、1ならotherColorと同じ。
func lerp(_ otherColor: UIColor, rate: CGFloat) -> UIColor {
var r1: CGFloat = 0, g1: CGFloat = 0, b1: CGFloat = 0, a1: CGFloat = 0, r2: CGFloat = 0, g2: CGFloat = 0, b2: CGFloat = 0, a2: CGFloat = 0
self.getRed(&r1, green: &g1, blue: &b1, alpha: &a1)
otherColor.getRed(&r2, green: &g2, blue: &b2, alpha: &a2)
let lerp = _lerpCurried(rate)
return UIColor(
red: lerp(r1, r2),
green: lerp(g1, g2),
blue: lerp(b1, b2),
alpha: lerp(a1, a2)
)
}
}
extension CGFloat {
func lerp(_ otherValue: CGFloat, rate: CGFloat) -> CGFloat {
let lerp = _lerpCurried(rate)
return lerp(self, otherValue)
}
}
private func _lerpCurried(_ rate: CGFloat) -> (CGFloat, CGFloat) -> CGFloat {
let rateInversed = 1 - rate
return { from, to in from * rateInversed + to * rate }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment