Search code examples
iosswiftuibezierpath

Draw a line with UIBezierPath


First time using BezierPaths, wondering how this function is actually supposed to be implemented. Currently the bezier path moves within the frame of the image, as opposed to drawing on screen.

Is there a better way to do it?

func drawLineFromPoint(start : CGPoint, toPoint end:CGPoint, ofColor lineColor: UIColor, inView view:UIView) {

    var maxWidth = abs(start.x - end.x)
    var maxHeight = abs(start.y - end.y)

    var contextSize : CGSize!
    if maxWidth == 0 {
        contextSize = CGSize(width: 1, height: maxHeight)
    }else {
        contextSize = CGSize(width: maxWidth, height: 1)
    }

    //design the path
    UIGraphicsBeginImageContextWithOptions(contextSize, false, 0)
    var path = UIBezierPath()
    path.lineWidth = 1.0
    lineColor.set()

    //draw the path and make visible
    path.moveToPoint(start)
    path.addLineToPoint(end)
    path.stroke()

    //create image from path and add to subview
    var image = UIGraphicsGetImageFromCurrentImageContext()
    var imageView = UIImageView(image: image)
    view.addSubview(imageView)
    UIGraphicsEndImageContext()
}

Solution

  • Ended up doing it this way:

    func drawLineFromPoint(start : CGPoint, toPoint end:CGPoint, ofColor lineColor: UIColor, inView view:UIView) {
        
        //design the path
        let path = UIBezierPath()
        path.move(to: start)
        path.addLine(to: end)
        
        //design path in layer
        let shapeLayer = CAShapeLayer()
        shapeLayer.path = path.cgPath
        shapeLayer.strokeColor = lineColor.CGColor
        shapeLayer.lineWidth = 1.0
        
        view.layer.addSublayer(shapeLayer)
    }