I know use UIBezierPath() to draw a dash line like:
let path = UIBezierPath()
path.setLineDash([CGFloat(4), CGFloat(4)], count: 2, phase: 0)
path.lineCapStyle = CGLineCap.round
path.move(to: startPoint)
path.addLine(to: endPoint)
path.stroke()
It works fine. But how could I can draw a dash line in context? Like below code can draw a solid line no matter if i add
context.setLineDash(phase: 3, lengths: [3,2])
The whole code:
override func draw(_ rect: CGRect) {
if let context = UIGraphicsGetCurrentContext() {
let startPoint = CGPoint(x: 50, y: 10)
let endPoint = CGPoint(x: rect.width-100, y: 10)
context.setLineDash(phase: 3, lengths: [3,2])
context.setLineWidth(10)
context.move(to: startPoint)
context.addLine(to: endPoint)
context.setStrokeColor(UIColor.red.cgColor)
context.setLineCap(.round)
context.strokePath()
}
}
The result is:
Anything wrong?
Think about it...
The line width is 10. The line cap is round. So the radius of the line cap is 5.
N.B. The line ends at the centre point of the line cap (not at the end of the cap).
The length of each dash is 3 and the gap between the lines is 2.
So the radius of the cap is much much bigger than the gap between the lines. So each line is overlapping to the next one.
Try making the line lengths like...
[3, 12]
That should make the lines 3 points long with a cap radius of 5 and then a gap between the ends of the caps of 2 (12 - 5 - 5).