Spring 旋转动画在开始处结束

Spring animation for rotation that ends where it began

我想为旋转创建一个 CASSpringAnimation,它在开始的地方结束。这是一些工作代码,不会在它开始的地方结束(但除此之外是我正在寻找的):

func spring(view: UIView) -> CASpringAnimation{
    let animation = CASpringAnimation(keyPath: "transform")
    animation.damping = 0.5
    animation.initialVelocity = 70
    animation.mass = 0.04
    animation.stiffness = 12
    animation.duration = 1.2
    animation.toValue = CATransform3DRotate(CATransform3DMakeAffineTransform(view.transform),
                                            CGFloat(M_PI)/32, // Must be non-zero 
                                            0, 0, 1)
    return animation
}

下面是您的使用方法:

    let animation = spring(view: viewToAnimate)
    viewToAnimate.layer.add(animation, forKey: nil)

当我将角度(在 CATransform3DRotate 中的注释旁边)设置为 0 时,动画不起作用!关于如何获得具有相同开始和结束角度的 spring 旋转的任何想法?感谢阅读。

通过添加一个 CABasicAnimation 在相同的持续时间内动画到 0°,并通过调整 spring 动画参数,我得到了一些看起来不错的东西(针对 iOS 进行了测试10):

@IBAction func springButtonTapped(_ sender: UIButton) { // Attach to the view you'd like animated
    let springAnim = spring(view:sender)
    sender.layer.add(springAnim, forKey: nil)

    let correctionAnim = correct(view:sender)
    sender.layer.add(correctionAnim, forKey: nil)
}

func correct(view: UIButton) -> CABasicAnimation{
    let animation = CABasicAnimation(keyPath: "transform")
    animation.duration = 0.3
    animation.toValue = CATransform3DRotate(CATransform3DMakeAffineTransform(view.transform),
                                            0,
                                            0, 0, 1)
    return animation
}

func spring(view: UIView) -> CASpringAnimation{
    let animation = CASpringAnimation(keyPath: "transform")
    animation.damping = 0.0
    animation.initialVelocity = 80
    animation.mass = 0.04
    animation.stiffness = 50
    animation.duration = 0.3
    animation.toValue = CATransform3DRotate(CATransform3DMakeAffineTransform(view.transform),
                                            CGFloat(M_PI)/64,
                                            0, 0, 1)
    return animation
}