
[英]How to add animation on CGAffineTransform for rotationAngle in SwiftUI?
[英]How to make rotation animation with CGAffineTransform in SwiftUI?
在我的指南针应用程序中,出于某些原因,我必须使用 CGAffineTransform 来旋转我的箭头。 但我不知道如何使用 CGAffineTransform 创建 animation。
我的代码:
import SwiftUI
import CoreLocation
struct Arrow: View {
var locationManager = CLLocationManager()
@ObservedObject var location: LocationManager = LocationManager()
@State private var angle: CGFloat = 0
var body: some View {
VStack {
Image("arrow")
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 300, height: 300)
.modifier(RotationEffect(angle: CGFloat(self.location.heading.degreesToRadians)))
Text(String(self.location.heading.degreesToRadians))
.font(.system(size: 20))
.fontWeight(.light)
.padding(.top, 15)
Text(String(self.location.coordinates[0]))
.font(.system(size: 20))
.fontWeight(.light)
.padding(.top, 15)
Text(String(self.location.coordinates[1]))
.font(.system(size: 20))
.fontWeight(.light)
.padding(.top, 15)
}
}
}
struct RotationEffect: GeometryEffect {
var angle: CGFloat
var animatableData: CGFloat {
get { angle }
set { angle = newValue }
}
func effectValue(size: CGSize) -> ProjectionTransform {
return ProjectionTransform(
CGAffineTransform(translationX: -150, y: -150)
.concatenating(CGAffineTransform(rotationAngle: angle))
.concatenating(CGAffineTransform(translationX: 150, y: 150))
)
}
}
我知道我可以像下面的代码一样使用withAnimation
,但我需要使用我的 location.heading 自动设置角度变量。 无需按任何按钮。
struct ContentView: View {
@State private var angle: CGFloat = 0
var body: some View {
VStack {
Rectangle()
.frame(width: 50, height: 50)
.modifier(MyEffect(angle: angle))
Button("Go to 0") {
withAnimation(.easeInOut(duration: 2.0)) {
self.angle = 0
}
}
Button("Go to 360") {
withAnimation(.easeInOut(duration: 2.0)) {
self.angle = .pi * 2
}
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.