ios - 在 SwiftUI 中平滑地加速旋转

标签 ios swift swiftui

我想在 SwiftUI 应用程序中平滑地加速形状的旋转速度,然后再次将其减慢到固定速度。首先,我尝试像使用任何其他属性(例如 .speed(speedUp ? 5.0 : 1.0))一样使用 @State Bool 来切换动画速度), 但我认为动画属性本身不是可动画的。我也试过使用 AnimatableModifier 无效:

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

最佳答案

您可以尝试.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:) 参数的含义,尝试了来自 this github 的一些示例. 描述了更复杂的动画 in this article ,应该有用

关于ios - 在 SwiftUI 中平滑地加速旋转,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59597619/

相关文章:

ios - 如何以编程方式填充 switch case 值?

ios - SwiftUI:如何 "swipe delete"嵌套 ForEach 中的元素(分组)

iphone - 删除 View 并弹出后将 nil 分配给 UIViewController 时崩溃

ios - 在 Swift 中通过 TouchID 生成哈希或字符串

swift - 如何保存从 UIPickerController 中选取的多张图像?

ios - 返回 Nil 的 MPMediaItem 发布日期(Swift 4)

SwiftUI Charts 如何向选定(或最后一个)BarMark 添加指示线

swiftui - ContentView (SwiftUI) 的背景图像不是 subview ,但具有正确的滚动行为

iOS触发方向改变事件

ios - 在 UIToolbar 上创建左箭头按钮(如 UINavigationBar 的 "back"样式)