如何从更简单的 UISpringTimingParameter 初始值设定项派生 CASSpringAnimation 属性?

How to derive CASpringAnimation properties from simpler UISpringTimingParameter initializer?

我有一条 spring 动画曲线,使用他们的 UISpringTimingParameters with damping ratio and initial velocity, and I use it with a UIViewPropertyAnimator with its duration specified. Elsewhere in my app, I need to express the same animation using CASpringAnimation. But CASpringAnimation can't be initialized with just a damping ratio and initialVelocity - it requires all the different spring parameters and derives its settlingDuration 指定。

给定持续时间、阻尼比和初始速度向量,如何创建 CASpringAnimation

抱歉,我无法帮助您计算数学,但也许您可以使用虚拟 属性 动画师来计算您需要的内容?参见 https://developer.apple.com/videos/play/wwdc2016/216/?time=2521

func animationDuration() -> TimeInterval {
    return propertyAnimator().duration
}

func propertyAnimator(initialVelocity: CGVector = .zero) -> UIViewPropertyAnimator {
    let timingParameters = UISpringTimingParameters(mass: 4.5, stiffness: 1300, damping: 95, initialVelocity: initialVelocity)
    return UIViewPropertyAnimator(duration: assetTransitionDuration, timingParameters:timingParameters)
}

我在 blog post 上找到了答案。简而言之:

let spring = CASpringAnimation(keyPath: somePropertyPath)

//Set initial velocity and desired duration
let initialVelocity: CGFloat = desiredInitialVelocity
let relaxationTime: CGFloat = desiredDurationInSeconds

//Spring constants
let dampingRatio: CGFloat = 0.9
//Only allow damping ratio between just above 0 and 1 (critically damped)
let clippedDampingRatio: CGFloat = min(1, max(dampingRatio, 0.01))
let mass: CGFloat = 1
let fractionOfAmplitude: CGFloat = 1500 //A spring never gets to 0 amplitude, it gets infinitely smaller. This fraction represents the perceived 0 point.
let logOfFraction: CGFloat = log(fractionOfAmplitude)
let stiffness: CGFloat = (mass * pow(logOfFraction, 2)) / (pow(relaxationTime, 2) * pow(clippedDampingRatio, 2))
let angularFrequency: CGFloat = sqrt(stiffness/mass)
let damping: CGFloat = 2 * mass * angularFrequency * clippedDampingRatio

spring.initialVelocity = initialVelocity
spring.mass = mass
spring.stiffness = stiffness
spring.damping = damping