如何用鼠标在 SwiftUI 中画一条线?

iOS*_*com 1 swiftui

我正在尝试做这样的事情,但我不知道从哪里开始。

在此处输入图片说明

到目前为止,我有一些“有效”的代码......这是我的完整代码(macOS)

struct ContentView: View {
    @State private var currentPosition: CGSize = .zero
    @State private var newPosition: CGSize = .zero

    var body: some View {
        ZStack {
            Path { path in
                path.move(to: CGPoint(x: 20, y: 100))
                path.addLine(to: CGPoint(x: currentPosition.width, y: currentPosition.height))
            }
            .trimmedPath(from: 0, to: 1)
            .strokedPath(StrokeStyle(lineWidth: 9, lineCap: .square, lineJoin: .round))
            .foregroundColor(.red)
            Circle()
                .frame(width: 7, height: 7)
                .foregroundColor(Color.blue)
                .offset(x: self.currentPosition.width, y: self.currentPosition.height)
                .gesture(DragGesture()
                    .onChanged { value in
                        self.currentPosition = CGSize(width: value.translation.width + self.newPosition.width, height: value.translation.height + self.newPosition.height)
                }
                .onEnded { value in
                    self.currentPosition = CGSize(width: value.translation.width + self.newPosition.width, height: value.translation.height + self.newPosition.height)
                    print(self.newPosition.width)
                    self.newPosition = self.currentPosition
                }
            )
            Color.clear
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但是我的蓝色圆圈离矩形很远。请问有什么帮助吗?

sta*_*Man 5

你只是缺少positionCircle

struct ContentView: View {
  @State private var startPoint: CGPoint = .zero
  @State private var endPoint: CGPoint = CGPoint(x: 100, y: 100)

  var body: some View {
    ZStack {
      Path { (path) in
        path.move(to: startPoint)
        path.addLine(to: endPoint)
      }
      .strokedPath(StrokeStyle(lineWidth: 9, lineCap: .square, lineJoin: .round))
      .foregroundColor(.red)

      //Circle 1
      Circle()
        .frame(width: 16, height: 16)
        .position(startPoint)
        .foregroundColor(.blue)
        .gesture(DragGesture()
          .onChanged { (value) in
            self.startPoint = CGPoint(x: value.location.x, y: value.location.y)
        })

      //Circle 2
      Circle()
        .frame(width: 16, height: 16)
        .position(endPoint)
        .foregroundColor(.green)
        .gesture(DragGesture()
        .onChanged { (value) in
          self.endPoint = CGPoint(x: value.location.x, y: value.location.y)
        })
      Color.clear
    }
  }
}
Run Code Online (Sandbox Code Playgroud)