How to draw a line in Swift 3
Asked Answered
H

2

15

I would like the user to touch 2 points and then a line is drawn between those two points. Here is what I have so far:

func drawline(){
    let context = UIGraphicsGetCurrentContext()
    context!.beginPath()
    context?.move(to: pointA)
    context?.addLine(to: pointB)
    context!.strokePath()
}

pointA is the first point the user touched and pointB is the second point. I get the error:

thread 1:EXC_BREAKPOINT

Thanks in advance for your help.

Hypochondriac answered 11/11, 2016 at 20:58 Comment(0)
I
30

To draw a line between two points the first thing you need is get the CGPoints from the current UIView, there are several ways of achieve this. I going to use an UITapGestureRecognizer for the sake of the sample to detect when you make a tap.

The another step is once you have the two points saved draw the line between the two points, and for this again you can use the graphics context as you try before or use CAShapeLayer.

So translating the explained above we get the following code:

class ViewController: UIViewController {

   var tapGestureRecognizer: UITapGestureRecognizer!

   var firstPoint: CGPoint?
   var secondPoint: CGPoint?

   override func viewDidLoad() {
       super.viewDidLoad()

       tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.showMoreActions(touch:)))
       tapGestureRecognizer.numberOfTapsRequired = 1
       view.addGestureRecognizer(tapGestureRecognizer)
   }

   func showMoreActions(touch: UITapGestureRecognizer) {
       let touchPoint = touch.location(in: self.view)

       guard let _ = firstPoint else {
           firstPoint = touchPoint
           return
       }

       guard let _  = secondPoint else {
           secondPoint = touchPoint
           addLine(fromPoint: firstPoint!, toPoint: secondPoint!)

           firstPoint = nil
           secondPoint = nil

           return
       }
   }

   func addLine(fromPoint start: CGPoint, toPoint end:CGPoint) {
       let line = CAShapeLayer()
       let linePath = UIBezierPath()
       linePath.move(to: start)
       linePath.addLine(to: end)
       line.path = linePath.cgPath
       line.strokeColor = UIColor.red.cgColor
       line.lineWidth = 1
       line.lineJoin = kCALineJoinRound
       self.view.layer.addSublayer(line)
   }
}

The above code is going to draw a line every time two points are selected and you can customize the above function as you like.

I hope this help you.

Ichang answered 11/11, 2016 at 21:52 Comment(3)
thanks! I have another question: How can i delete the lines the user has drawmHypochondriac
@CharlesB. You're welcome, you can remove the previous CAShapeLayer (with removeFromSuperlayer) saving the references, it's just a way to do itIchang
@Victor, I used your func addline and it works to draw one line inside a Cell. thanksHuynh
S
1

Draw line in Swift 4.1

class MyViewController: UIViewController {

    @IBOutlet weak var imgViewDraw: UIImageView!

    var lastPoint = CGPoint.zero
    var red: CGFloat = 0.0
    var green: CGFloat = 0.0
    var blue: CGFloat = 0.0
    var brushWidth: CGFloat = 10.0
    var opacity: CGFloat = 1.0
    var isSwiping:Bool!


    override func viewDidLoad() {
        super.viewDidLoad()


    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    //MARK: Touch events
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        isSwiping    = false
        if let touch = touches.first{
            lastPoint = touch.location(in: imgViewDraw)
        }
    }
    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {

        isSwiping = true;
        if let touch = touches.first{
            let currentPoint = touch.location(in: imgViewDraw)
            UIGraphicsBeginImageContext(self.imgViewDraw.frame.size)
            self.imgViewDraw.image?.draw(in: CGRect(x:0, y:0,width:self.imgViewDraw.frame.size.width, height:self.imgViewDraw.frame.size.height))

            UIGraphicsGetCurrentContext()?.move(to: CGPoint(x: lastPoint.x, y: lastPoint.y))
            UIGraphicsGetCurrentContext()?.addLine(to: CGPoint(x: currentPoint.x, y: currentPoint.y))

            UIGraphicsGetCurrentContext()?.setLineCap(CGLineCap.round)
            UIGraphicsGetCurrentContext()?.setLineWidth(self.brushWidth)
            UIGraphicsGetCurrentContext()?.setStrokeColor(red: red, green: green, blue: blue, alpha: 1.0)
            UIGraphicsGetCurrentContext()?.strokePath()


            self.imgViewDraw.image = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            lastPoint = currentPoint
        }
    }
    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        if(!isSwiping) {
            // This is a single touch, draw a point
            UIGraphicsBeginImageContext(self.imgViewDraw.frame.size)
            self.imgViewDraw.image?.draw(in: CGRect(x:0, y:0,width:self.imgViewDraw.frame.size.width, height:self.imgViewDraw.frame.size.height))
            UIGraphicsGetCurrentContext()?.setLineCap(CGLineCap.round)
            UIGraphicsGetCurrentContext()?.setLineWidth(self.brushWidth)

            UIGraphicsGetCurrentContext()?.move(to: CGPoint(x: lastPoint.x, y: lastPoint.y))
            UIGraphicsGetCurrentContext()?.addLine(to: CGPoint(x: lastPoint.x, y: lastPoint.y))
            UIGraphicsGetCurrentContext()?.setStrokeColor(red: red, green: green, blue: blue, alpha: 1.0)
            UIGraphicsGetCurrentContext()?.strokePath()
            self.imgViewDraw.image = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
        }
    }


}
Sharisharia answered 20/10, 2018 at 10:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.