SwiftUI实现矩形沿指定路径拖动的问题求助
让自定义矩形沿指定路径移动的实现问题
我想让自定义矩形只能沿着指定路径移动,但不清楚具体实现方法。以下是我目前的实现代码:
struct _FollowingPathView: View { @State private var position = CGSize() @State private var finalPosition = CGSize() @State private var currentPosition: CGFloat = 0.5 var body: some View { VStack { Rectangle() .frame(width: 300, height: 300) .foregroundColor(.clear) .border(.black, width: 2) .overlay { CustomPath().path(in: CGRect(x: 0, y: 0, width: 300, height: 300)) .stroke(Color.red, style: StrokeStyle(lineWidth: 2)) Rectangle() .frame(width: 50, height: 50) .foregroundColor(.clear) .border(.black, width: 2) .offset( ) .gesture( DragGesture(minimumDistance: 0) .onChanged { position.width = min(max(-125, $0.translation.width + finalPosition.width), 125) position.height = min(max(-125, $0.translation.height + finalPosition.height), 125) } .onEnded { position.width = min(max(-125, $0.translation.width + finalPosition.width), 125) position.height = min(max(-125, $0.translation.height + finalPosition.height), 125) finalPosition = position } ) } } } } struct _FollowingPathView_Previews: PreviewProvider { static var previews: some View { _FollowingPathView() } }
我曾尝试使用trimmedPath并通过DragGesture修改currentPosition,但无法正常工作,相关代码片段如下:
.position( x: CustomPath().path(in: CGRect(x: 0, y: 0, width: 300, height: 300)).trimmedPath(from: 0, to: currentPosition).currentPoint?.x ?? CGPoint(), y: CustomPath().path(in: CGRect(x: 0, y: 0, width: 300, height: 300)).trimmedPath(from: 0, to: currentPosition).currentPoint?.y ?? CGPoint(), )
内容的提问来源于stack exchange,提问作者TooMaaSens
相关产品推荐
相关产品推荐

