首页 > 解决方案 > Smoothly speed up rotation in SwiftUI

问题描述

I would like to smoothly accelerate the rotation speed of a shape in a SwiftUI application then slow it back down again to fixed speed. First I tried toggling the animation speed using a @State Bool as I would any other property (e.g. .speed(speedUp ? 5.0 : 1.0)), but I suppose animation properties themselves are not themselves animatable. I've also tried using an AnimatableModifier to no effect:

import SwiftUI

struct SpeedModifier: AnimatableModifier {
    var speed: Double
    var animatableData: Double {
        get { speed }
        set { speed = newValue }
    }

    func body(content: Content) -> some View {
        return content.animation(
                Animation
                    .linear(duration: 5.0)
                    .speed(speed)
                    .repeatForever(autoreverses: false)
            )
    }
}

struct SwiftUIView: View {
    @State var isRotating = false
    @State var speedUp = false
    var body: some View {
        Rectangle()
            .frame(width: 200, height: 200)
            .rotationEffect(.degrees(isRotating ? 360 : 0))
            .modifier(SpeedModifier(speed: speedUp ? 5.0 : 1.0))
            .onAppear {
                self.isRotating.toggle()
                DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
                    self.speedUp.toggle()
                }
            }
    }
}

struct SwiftUIView_Previews: PreviewProvider {
    static var previews: some View {
        SwiftUIView()
    }
}

标签: iosswiftswiftui

解决方案


你可以试试.timingCurve动画。在这个例子中,矩形一直旋转得越来越慢:

struct RotatingView: View {

    @State private var rotationDegree = 0.0
    private var timeCurveAnimation: Animation {
        return Animation.timingCurve(0.5, 0.8, 0.8, 0.3, duration: 6)
            .repeatForever(autoreverses: false)
    }

    var body: some View {
        Rectangle()
            .frame(width: 200, height: 200)
            .rotationEffect(.degrees(rotationDegree))
            .onAppear() {
                withAnimation(self.timeCurveAnimation) {
                    self.rotationDegree = 720.0
                }
        }
    }

}

不幸的是,几乎没有文档 ( c0x:c0y:c1x: c1y:) 参数是什么意思,尝试了一些来自这个 github的示例。这篇文章中描述了更复杂的动画,应该很有用


推荐阅读