Created
March 11, 2020 23:47
-
-
Save edwardsanchez/a46c0eb6fbc5030541a23bd67e543de9 to your computer and use it in GitHub Desktop.
Spring Animation Playground - Calculating stiffness and damping with a given duration and dampingRatio.
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
//: A UIKit based Playground for presenting user interface | |
import UIKit | |
import PlaygroundSupport | |
class MyViewController : UIViewController { | |
override func loadView() { | |
let view = UIView() | |
view.backgroundColor = .white | |
self.view = view | |
//Edit these | |
let duration: CGFloat = 0.35 | |
let dampingRatio: CGFloat = 1 | |
let purpleSquare = UIView() | |
purpleSquare.frame = CGRect(x: 135, y: 200, width: 50, height: 50) | |
purpleSquare.backgroundColor = .systemPurple | |
view.addSubview(purpleSquare) | |
let purpleAnimation = UIViewPropertyAnimator(duration: TimeInterval(duration), dampingRatio: dampingRatio, animations: { | |
purpleSquare.frame.origin.y += 200 | |
}) | |
let blueSquare = UIView() | |
blueSquare.frame = CGRect(x: purpleSquare.frame.origin.x + 55, y: purpleSquare.frame.origin.y, width: 50, height: 50) | |
blueSquare.backgroundColor = .systemBlue | |
view.addSubview(blueSquare) | |
//Formula for calculating damping and stiffness given duration and dampingRatio (value from >0 to 1) | |
let fractionOfAmplitude: CGFloat = 1/10000 | |
let mass: CGFloat = 1 | |
let damping: CGFloat = (-2 * mass * log(fractionOfAmplitude)) / duration | |
let stiffness: CGFloat = pow(damping,2) / (4 * pow(dampingRatio, 2)) * mass | |
let blueAnimation = UIViewPropertyAnimator(duration: 0, timingParameters: UISpringTimingParameters(mass: 1, stiffness: stiffness, damping: damping, initialVelocity: CGVector(dx: 0, dy: 0))) | |
blueAnimation.addAnimations { | |
blueSquare.frame.origin.y += 200 | |
} | |
purpleAnimation.startAnimation(afterDelay: 2) | |
blueAnimation.startAnimation(afterDelay: 2) | |
} | |
} | |
// Present the view controller in the Live View window | |
PlaygroundPage.current.liveView = MyViewController() |
This really helped me today when trying to make a SwiftUI spring animation match a UIKit spring animation. Thank you for this!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Purple square uses the regular UIViewPropertyAnimator that you can use in most cases.
The blue square uses a spring, which you might need to use if you must animate a CALayer. The formulas on lines 33 and 34 show you how to calculate the damping and stiffness, given a dapingRatio and duration.