Charles B. Charles B. - 1 year ago 243
Swift Question

How to draw a line in Swift 3

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?.move(to: pointA)
context?.addLine(to: pointB)

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


Thanks in advance for your help.

Answer Source

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() {

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

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

       guard let _ = firstPoint else {
           firstPoint = touchPoint

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

           firstPoint = nil
           secondPoint = nil


   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 =
       line.lineWidth = 1
       line.lineJoin = kCALineJoinRound

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download