Skip to content

Instantly share code, notes, and snippets.

@heestand-xyz
Last active February 5, 2019 10:11
Show Gist options
  • Save heestand-xyz/2b118cdb8667a25b506f5b11e162f9e7 to your computer and use it in GitHub Desktop.
Save heestand-xyz/2b118cdb8667a25b506f5b11e162f9e7 to your computer and use it in GitHub Desktop.
Animate with Ease
enum AnimationEase {
case linear
case easeIn
case easeInOut
case easeOut
}
func animate(for duration: CGFloat, ease: AnimationEase = .linear, loop: @escaping (CGFloat) -> (), done: @escaping () -> ()) {
let startTime = Date()
RunLoop.current.add(Timer(timeInterval: 1.0 / Double(UIScreen.main.maximumFramesPerSecond), repeats: true, block: { t in
let elapsedTime = CGFloat(-startTime.timeIntervalSinceNow)
let fraction = min(elapsedTime / duration, 1.0)
var easeFraction = fraction
switch ease {
case .linear: break
case .easeIn: easeFraction = cos(fraction * .pi / 2 - .pi) + 1
case .easeInOut: easeFraction = cos(fraction * .pi - .pi) / 2 + 0.5
case .easeOut: easeFraction = cos(fraction * .pi / 2 - .pi / 2)
}
loop(easeFraction)
if fraction == 1.0 {
done()
t.invalidate()
}
}), forMode: .common)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment