swiftuibezierpathcashapelayercgpointtouchesbegan

draw line using uibezierPath in a vertical way


My swift code below draws a horiziontal way the horizontal line is at a angle that does not change. Think like a x axis. I want to draw a line in the exact opposite way. Think of the y axis. The line is drawn at

bezier.addLine(to: CGPoint(x: point.x, y: startPoint!.y))

    import UIKit
class ViewController: UIViewController {
    @IBOutlet weak var imageView: UIImageView!
    
    var startPoint: CGPoint?

    let shapeLayer: CAShapeLayer = {
        let shapeLayer = CAShapeLayer()
        shapeLayer.lineWidth = 4
        shapeLayer.fillColor = UIColor.clear.cgColor
        shapeLayer.strokeColor = UIColor.blue.cgColor
        return shapeLayer
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        imageView.backgroundColor = .systemOrange
        imageView.layer.addSublayer(shapeLayer)
    }

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

    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        guard var touch = touches.first else { return }

        if let predicted = event?.predictedTouches(for: touch)?.last {
            touch = predicted
        }

        updatePath(in: imageView, to: touch)
    }

    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        guard let touch = touches.first else { return }
        updatePath(in: imageView, to: touch)
        let image = UIGraphicsImageRenderer(bounds: imageView.bounds).image { _ in
            imageView.drawHierarchy(in: imageView.bounds, afterScreenUpdates: true)
        }
        shapeLayer.path = nil
        imageView.image = image
    }
}

private extension ViewController {
    func updatePath(in view: UIView, to touch: UITouch) {
        let point = touch.location(in: view)
        guard view.bounds.contains(point) else { return }

        let bezier = UIBezierPath()

        bezier.move(to: startPoint!)
        bezier.addLine(to: CGPoint(x: point.x, y: startPoint!.y))

        shapeLayer.path = bezier.cgPath
    }
}

Solution

  • Actually you move on to startPoint and trying to add line to the same static point ... how it can add line to the same point on which you are currently residing ... add some value to Y while static X position position to add line

     bezier.move(to: startPoint!)
      bezier.addLine(to: CGPoint(x: startPoint!.x, y: point.y))