我有一个观点,我希望能够四处游荡——有点像命运的非自由旋转轮。拖动在 y 轴和轮子底部工作正常,但使用 x - 拖动轮子顶部时视图以错误的方向旋转。
我很确定这只需要一点额外的逻辑 - 但我尝试过的所有东西都不起作用 - 例如检查是否v.startLocation.x < v.location.x
.
import SwiftUI
struct SpinningSelectorWheel: View {
var numberOfSegments: Int = 5
private var colorArray:[Color] = [.red, .green, .blue, .yellow, .brown, .gray, .purple, .red, .green, .blue, .yellow, .brown, .gray, .purple]
@State private var angle: CGFloat = 0
@State private var lastAngle: CGFloat = 0
@State private var length : CGFloat = 400
@State private var gtheta: CGFloat = 0
@State private var gstartx: CGFloat = 0
@State private var gstarty: CGFloat = 0
var body: some View {
GeometryReader
{ fullsize in
//Text("\(angle)")
VStack
{
Text("\(gtheta)")
Text("\(gstartx)")
Text("\(gstarty)")
Text("\(length)")
}
ForEach((1...numberOfSegments).reversed(), id: \.self)
{segment in
Path { path in
path.move(to: CGPoint(x: fullsize.size.width/2, y: fullsize.size.height/2))
path.addArc(center: .init(x: fullsize.size.width/2, y: fullsize.size.height/2), radius: 150, startAngle: Angle(degrees: Double(1-segment) * Double(360/numberOfSegments)), endAngle: Angle(degrees: Double(360/numberOfSegments)), clockwise: false)
}
.fill(colorArray[segment-1])
}
.rotationEffect(.degrees(Double(self.angle))).gesture(DragGesture().onChanged
{ v in
var theta = (atan2(v.location.x - self.length / 2, self.length / 2 - v.location.y) - atan2(v.startLocation.x - self.length / 2, self.length / 2 - v.startLocation.y)) * 180 / .pi
gtheta = theta
gstartx = v.startLocation.x
gstarty = v.startLocation.y
if (theta < 0) { theta += 360}
self.angle = theta + self.lastAngle
}
.onEnded { v in
self.lastAngle = self.angle
}
)
}
}
}