Swift Draw Lines on Your View
CAShape Tool Shared.
Result like~
- sample code from Online
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)
}
}