【问题标题】:Rotation animation with spring effect具有弹簧效果的旋转动画
【发布时间】:2016-07-31 09:27:51
【问题描述】:

我想用弹簧效果(如UIView.animateWithDuration(_:delay:usingSpringWithDamping:initialSpringVelocity:options:animations:completion:))旋转 CAShapeLayer,但在图层上而不是在视图上。

点击按钮时,其主层的子层应旋转到 3*PI/4,弹簧应弹回到 2*PI/3。然后,当再次点击按钮时,图层旋转应该按照与之前相反的顺序进行:首先反弹到 2*PI/3,然后旋转到初始位置(第一次旋转之前)。

我怎么能做到这一点?我无法通过UIView.animateWithDuration(_:delay:usingSpringWithDamping:initialSpringVelocity:options:animations:completion:) 实现它,因为默认情况下图层的变换属性是可动画的。

我尝试更改CATransaction,但它只旋转一个角度(不考虑其他旋转):

let rotation1 = CGAffineTransformRotate(CGAffineTransformIdentity, angle1)
let rotation2 = CGAffineTransformRotate(CGAffineTransformIdentity, angle2)
let transform = CGAffineTransformConcat(rotation1, rotation2)
CATransaction.begin()
CATransaction.setAnimationDuration(0.6)
self.plusLayer.setAffineTransform(transform)
CATransaction.commit()

更新

根据Duncan C post,我尝试使用CASpringAnimation,并在一个方向上实现动画:

myLayer.setAffineTransform(CGAffineTransformMakeRotation(angle))
let spring = CASpringAnimation(keyPath: "transform.rotation")
spring.damping = 12.0
spring.fromValue = 2.0 * CGFloat(M_PI)
spring.toValue = 3.0 * CGFloat(M_PI_4)
spring.duration = 0.5
myLayer.addAnimation(spring, forKey: "rotation")

但是如何在点击按钮时反转该动画?

提前感谢您的帮助。

【问题讨论】:

    标签: ios swift animation core-graphics


    【解决方案1】:

    UIView 块动画用于动画视图属性。您可以使用UIView.animateWithDuration(_:delay:usingSpringWithDamping:initialSpringVelocity:options:animations:completion: 为按钮的变换(CGAffineTransform 类型,一种 2D 变换)设置动画。

    但是,如果您需要为图层属性设置动画,则需要使用 Core Animation。

    Apple 似乎在 iOS 9 中添加(或公开)了 Spring CAAnimation。但它似乎不在 Xcode 文档中。

    看看这个帖子:

    SpringWithDamping for CALayer animations?

    【讨论】:

    • 谢谢!这对我帮助很大!但是我还有一个问题:如何在点击按钮时反转动画?
    • 这里有一种方法可以做到:创建实例变量来跟踪当前的 from 和 to 旋转值,并在每次单击按钮时切换它们。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多