如何使图像旋转(animation)

我有一个广场的形象,我知道如何让它旋转。 animation旋转…然后停下来…然后再旋转…等等。

我只是一个基本的旋转,但不像上面的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) } } 

任何想法如何做到这一点?

您需要使用加速和减速的定时function,也称为易于定位function。

我已经修改了你的函数来使用Core Animation的标准易放出定时function:

 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) } } 

结果:

演示

请注意,在您的图像,它看起来像框每隔180度暂停,所以我已经改变了function旋转只有180度。 由于盒子具有90度的径向对称性,它仍然看起来像是一直在180度和360度之间停顿。

如果您需要在没有任何径向对称的情况下对图像进行animation处理,则需要使用CAKeyframeAnimation来实现180度和360度的轻松自如。

类似的效果也可以通过delay的重复animation来实现。

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