我想在 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/