开发 iOS App 时,我们有很多方法可以实现重覆 360 度旋转的动画。接下来我们分别看看以下三种实现的方法,SwiftUI 的 animation,UIKit 的 UIViewPropertyAnimator & UIKit 的 CABasicAnimation。
SwiftUI 的 animation
struct ContentView: View { @State private var degrees: Double = 0 var body: some View { VStack { Image("peter") .rotationEffect(.degrees(degrees)) .animation(Animation.linear(duration: 5).repeatForever(autoreverses: false)) Text("我因為你而轉\n一圈一圈自轉") .font(.largeTitle)} .onAppear { self.degrees = 360 } } }
UIKit 的 UIViewPropertyAnimator
class RotateImageView: UIImageView {
func rotate() {
let animator = UIViewPropertyAnimator(duration: 5, curve: .linear) {[weak self] in
guard let self = self else { return }
self.transform = CGAffineTransform(rotationAngle: .pi)
}
animator.addAnimations {[weak self] in
guard let self = self else { return }
self.transform = self.transform.rotated(by: .pi)
}
animator.addCompletion {[weak self] (_) in
guard let self = self else { return }
self.rotate()
}
animator.startAnimation()
}
}
UIKit 的 CABasicAnimation
class RotateImageView: UIImageView {
func rotate() {
let rotateAnimation = CABasicAnimation(keyPath: “transform.rotation”)
rotateAnimation.toValue = Double.pi * 2
rotateAnimation.duration = 5
rotateAnimation.repeatCount = .infinity
layer.add(rotateAnimation, forKey: nil)
}}
若想要画面一出现就呼叫 rotate 开始动画,记得要在 viewWillAppear 或 viewDidAppear 再加入 CABasicAnimation,在 viewDidLoad 加入的话动画将失效。
转载需保留链接来源:软件玩家 » Swift 实现无止尽 360 度旋转动画的三个方法