Search code examples
iosswiftcore-graphics

Drawing lines with core graphics


I want to draw more than one straight line in core graphics. or save the line and start a new one. I used two variables for touch location and assigned touch location to them in touch Began,Moved,Ended then I used this:

override func draw(_ rect: CGRect) {
    let context = UIGraphicsGetCurrentContext()
    context?.setStrokeColor(UIColor(red: 0, green: 0, blue: 0, alpha: 1.0).cgColor)
    context?.setLineWidth(5.0)
    context?.move(to: CGPoint(x: firstTouchLocation.x, y: firstTouchLocation.y))
    context?.addLine(to: CGPoint(x: lastTouchLocation.x, y: lastTouchLocation.y))
    context?.strokePath()
}

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first {
        firstTouchLocation = touch.location(in: self)
        lastTouchLocation = firstTouchLocation
        setNeedsDisplay()
    }
}

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first {
        lastTouchLocation = touch.location(in: self)
        setNeedsDisplay()
    }
}

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first {
        lastTouchLocation = touch.location(in: self)
        setNeedsDisplay()
    }
}

Solution

  • Try drawing the line using CAShapeLayer like so:

    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)
       }
    

    Hope this helps!