我正在尝试使用 canvas 和 detectorDragGestures 方法绘制直线,但到目前为止,我只实现了混沌行为,没有任何固定。我正在寻找解决方案以确保我的线条始终笔直。
import SwiftUI
struct GraphicDictView: View {
@State private var lines: [CGPoint] = []
@State private var circleToDraw = CGPoint()
var body: some View {
Canvas { context, _ in
context.fill(
Path(ellipseIn: CGRect(
x: circleToDraw.x - 7,
y: circleToDraw.y - 7,
width: 14,
height: 14
)),
with: .color(Color.blue)
)
var path = Path()
for line in lines {
path.addLine(to: line)
}
context.stroke(path, with: .color(Color.blue), lineWidth: 2)
}
.gesture(
DragGesture()
.onChanged { value in
circleToDraw = value.location
lines.append(value.location)
}
)
}
}
现在我的代码有这种行为:
您可以设置起点和终点并将它们添加到线数组中
//
// GraphicDictView.swift
// Meyollo
//
// Created by Hezy Ziv on 28/09/2024.
//
import SwiftUI
struct GraphicDictView: View {
@State private var startPoint: CGPoint?
@State private var endPoint: CGPoint?
@State private var lines: [(start: CGPoint, end: CGPoint)] = []
var body: some View {
Canvas { context, size in
for line in lines {
var path = Path()
path.move(to: line.start)
path.addLine(to: line.end)
context.stroke(path, with: .color(Color.blue), lineWidth: 2)
}
if let start = startPoint, let end = endPoint {
var path = Path()
path.move(to: start)
path.addLine(to: end)
context.stroke(path, with: .color(Color.blue), lineWidth: 2)
}
}
.gesture(
DragGesture()
.onChanged { value in
if startPoint == nil {
startPoint = value.location
}
endPoint = value.location
}
.onEnded { value in
if let start = startPoint {
lines.append((start: start, end: value.location))
}
startPoint = nil
endPoint = nil
}
)
}
}
#Preview {
GraphicDictView()
}