创建时让线条保持完美的 90 度

get line to remain a perfect 90 degrees when create

我的 swift 代码的目标是让每一行只能以 90 度角放置。现在代码有两个点,一个开始点和一个结束点,在触摸 uiview 时开始点是固定的。我希望用户能够触摸一个点并且只能以 90 度角延长线。查看下面的 gif 以获取更多信息。底线是我想要达到的目标。我觉得你得用guard in touches开始。

import UIKit

class ViewController2: UIViewController {

    @IBOutlet weak var drawingPlace: UIImageView!

    var startTouch : CGPoint?
    var secondTouch : CGPoint?
    var currentContext : CGContext?
    var prevImage : UIImage?


    override func viewDidLoad() {
        super.viewDidLoad()
    }


    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        let touch = touches.first
        startTouch = touch?.location(in: drawingPlace)
    }

    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {

        for touch in touches{
            secondTouch = touch.location(in: drawingPlace)

            if(self.currentContext == nil){
                UIGraphicsBeginImageContext(drawingPlace.frame.size)
                self.currentContext = UIGraphicsGetCurrentContext()
            }else{
                self.currentContext?.clear(CGRect(x: 0, y: 0, width: drawingPlace.frame.width, height: drawingPlace.frame.height))
            }

            self.prevImage?.draw(in: self.drawingPlace.bounds)

            let bezier = UIBezierPath()

            bezier.move(to: startTouch!)
            bezier.addLine(to: secondTouch!)
            bezier.close()

            UIColor.blue.set()

            self.currentContext?.setLineWidth(4)
            self.currentContext?.addPath(bezier.cgPath)
            self.currentContext?.strokePath()
            let img2 = self.currentContext?.makeImage()
            drawingPlace.image = UIImage.init(cgImage: img2!)

        }
    }


    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {

        self.currentContext = nil
        self.prevImage = self.drawingPlace.image
    }

}

问题出在这一行:

bezier.addLine(to: secondTouch!)

这会导致线条跟随触摸的位置,无论它在哪里。取而代之的是垂直于水平线(我假设这就是你所说的 90 度角)并将线添加到水平线上的那个点。换句话说,使用 secondTouchx 组件,但使用 startTouch.

y 组件作为 y 组件
bezier.addLine(to: CGPoint(x:secondTouch!.x, y:startTouch!.y)