ios - 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()
}
}
解决方案
你可以试试.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的示例。这篇文章中描述了更复杂的动画,应该很有用
推荐阅读
- javascript - core-js 版本冲突
- bash - 如何将参数传递给 curl 命令?
- java - 将 parseInt 更改为 nextInt
- java - 如何在 OnSwipeListener 之上为 GridView 实现 onClickListener?
- python - python不支持*的操作数类型:'int'和'function
- javascript - 在.Net Core中将数据从控制器传递到javascript
- reactjs - Redux 在任何 Firestore 条目更改后重新渲染整个表(React-Redux-Firebase + React-Virtualized)
- excel - 仅复制行的选定范围
- docker - 如何用新鲜或空气重建 go golang 应用程序?
- javascript - Next.js - 链接在生产中不起作用