Swift Draw Lines on Your View

Mario tsai
2 min readApr 29, 2021

--

CAShape Tool Shared.

Result like~

  1. sample code from Online
adjust everything (copy below)

2. Make a function for repeated using.

func addPointLine(p0: CGPoint,p1:CGPoint,pointerLineLength: CGFloat, arrowAng: CGFloat) -> CAShapeLayer{

let arrowLayer = CAShapeLayer()

arrowLayer.addArrowLine(p0: p0, p1: p1, pointerLineLength: pointerLineLength, arrowAng: arrowAng)

return arrowLayer

}

3. Add to your UIVIew()

vTableFirst.layer.addSublayer(

addPointLine(p0: opPointList[2], p1: selfPointList[3], pointerLineLength: 10, arrowAng: CGFloat(Double.pi / 12))

)

if you want to refresh, type

“ vTableFirst.layer.sublayers = nil

Sample

extension CAShapeLayer {

func addArrowLine(p0: CGPoint,p1:CGPoint,pointerLineLength: CGFloat, arrowAng: CGFloat){

let arrow = UIBezierPath()

arrow.addArrow(start: p0, end: p1, pointerLineLength: pointerLineLength, arrowAngle: arrowAng)

self.strokeColor = UIColor.black.cgColor

self.lineWidth = 3

self.path = arrow.cgPath

self.fillColor = UIColor.clear.cgColor

self.lineJoin = CAShapeLayerLineJoin.round

self.lineCap = CAShapeLayerLineCap.round

}

}

extension UIBezierPath {

func addArrow(start: CGPoint, end: CGPoint, pointerLineLength: CGFloat, arrowAngle: CGFloat) {

self.move(to: start)

self.addLine(to: end)

let startEndAngle = atan((end.y — start.y) / (end.x — start.x)) + ((end.x — start.x) < 0 ? CGFloat(Double.pi) : 0)

let arrowLine1 = CGPoint(x: end.x + pointerLineLength * cos(CGFloat(Double.pi) — startEndAngle + arrowAngle), y: end.y — pointerLineLength * sin(CGFloat(Double.pi) — startEndAngle + arrowAngle))

let arrowLine2 = CGPoint(x: end.x + pointerLineLength * cos(CGFloat(Double.pi) — startEndAngle — arrowAngle), y: end.y — pointerLineLength * sin(CGFloat(Double.pi) — startEndAngle — arrowAngle))

self.addLine(to: arrowLine1)

self.move(to: end)

self.addLine(to: arrowLine2)

}

}

--

--

Mario tsai

Major in physical education. Football referee. And high interest in looking the world through the numbers.