You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 11:05:22