Last active
November 24, 2020 06:57
-
-
Save ha1f/670c4566940832cad4c7c92452d7c8a1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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