2017-05-07 136 views
1

我有一个正方形的图像,我知道如何使它旋转。动画旋转......然后停下来......然后再旋转......等等。如何让图像旋转(动画)

我刚才是一个基本的旋转,但并不像上面的GIF:

extension UIView { 
    func rotate360Degrees(duration: CFTimeInterval = 3) { 
     let rotateAnimation = CABasicAnimation(keyPath: "transform.rotation") 
     rotateAnimation.fromValue = 0.0 
     rotateAnimation.toValue = CGFloat(M_PI * 2) 
     rotateAnimation.isRemovedOnCompletion = false 
     rotateAnimation.duration = duration 
     rotateAnimation.repeatCount=Float.infinity 
     self.layer.add(rotateAnimation, forKey: nil) 
    } 
} 

有什么想法就如何做到这一点?

回答

3

您需要使用加速和减速的定时功能,也称为易于放松定时功能。

我修改你的函数使用核心动画的标准易于在-渐出计时功能:

extension UIView { 
    func rotate360Degrees(duration: CFTimeInterval = 0.8) { 
     let rotateAnimation = CABasicAnimation(keyPath: "transform.rotation") 
     rotateAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) 
     let radians = CGFloat.pi/4 
     rotateAnimation.fromValue = radians 
     rotateAnimation.toValue = radians + .pi 
     rotateAnimation.isRemovedOnCompletion = false 
     rotateAnimation.duration = duration 
     rotateAnimation.repeatCount=Float.infinity 
     self.layer.add(rotateAnimation, forKey: nil) 
    } 
} 

结果:

demo

注意,在你的形象,它看起来盒子每隔180度就会暂停一次,所以我改变了旋转180度的功能。由于该盒子具有90度的径向对称性,它仍然看起来像是一路绕过,并在180度和360度处停顿。

如果您需要在没有任何径向对称的情况下对图像进行动画处理,则需要使用CAKeyframeAnimation来实现180度和360度的易于出入。

+0

哇,这很快,它完美的作品!非常感谢 - 如果你只知道我非常感谢帮助!你是最好的 : ) – JEL

0

重复动画与delay也可以实现类似的效果。

UIView.animate(withDuration: 1, 
         delay: 0.2, 
        options: [.repeat], 
       animations: { imageView.transform = imageView.transform.rotated(by: CGFloat.pi) }, 
       completion: nil)