在画布 SwiftUI 上绘制直线

问题描述 投票:0回答:1

我正在尝试使用 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)
            }
    )
  }
}

现在我的代码有这种行为:

enter image description here

我需要实现的行为: enter image description here

ios swift swiftui
1个回答
0
投票

您可以设置起点和终点并将它们添加到线数组中

//
//  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()
}
© www.soinside.com 2019 - 2024. All rights reserved.