draw line in swift

To draw a line in Swift, you can use the UIBezierPath class to create a path and then stroke it with a specific color and width.

Here's an example code snippet that draws a red line of 2 points width from point A to point B on an iOS view:

main.swift
let path = UIBezierPath()
path.move(to: CGPoint(x: pointA.x, y: pointA.y))
path.addLine(to: CGPoint(x: pointB.x, y: pointB.y))

let shapeLayer = CAShapeLayer()
shapeLayer.strokeColor = UIColor.red.cgColor
shapeLayer.lineWidth = 2.0
shapeLayer.path = path.cgPath

self.view.layer.addSublayer(shapeLayer)
303 chars
11 lines

In this code snippet, we create a UIBezierPath instance, move its initial point to pointA using the move(to:) method, then draw a line to pointB using the addLine(to:) method.

Next, we create a CAShapeLayer instance to hold the path and we set its stroke color and width to red and 2 points respectively. We set the path property of the shape layer to our UIBezierPath instance's cgPath representation.

Finally, we add the shape layer to the view's layer using the addSublayer method.

This will draw a red line on the screen from point A to point B.

gistlibby LogSnag