I am trying to draw dashed line with rounded corners around a view like this:
class DashedLineView: UIView {
override func draw(_ rect: CGRect) {
let path = UIBezierPath(roundedRect: rect, cornerRadius: 8)
UIColor.clear.setFill()
path.fill()
UIColor.red.setStroke()
path.lineWidth = 3
let dashPattern : [CGFloat] = [3, 3]
path.setLineDash(dashPattern, count: 2, phase: 0)
path.stroke()
}
}
The result is:
As you can see there is a problem with corners, any idea how to fix it?
Updated:
Using @Jon Rose answer DashedLineView
looks like this now:
class DashedLineView: UIView {
private let borderLayer = CAShapeLayer()
override func awakeFromNib() {
super.awakeFromNib()
borderLayer.strokeColor = UIColor.red.cgColor
borderLayer.lineDashPattern = [3,3]
borderLayer.backgroundColor = UIColor.clear.cgColor
borderLayer.fillColor = UIColor.clear.cgColor
layer.addSublayer(borderLayer)
}
override func draw(_ rect: CGRect) {
borderLayer.path = UIBezierPath(roundedRect: rect, cornerRadius: 8).cgPath
}
}
I have had good experience with using a CAShapeLayer. For example:
let rect = CGRect.init(origin: CGPoint.init(x: 20, y: 100), size: CGSize.init(width: 200, height: 100))
let layer = CAShapeLayer.init()
let path = UIBezierPath(roundedRect: rect, cornerRadius: 8)
layer.path = path.cgPath;
layer.strokeColor = UIColor.red.cgColor;
layer.lineDashPattern = [3,3];
layer.backgroundColor = UIColor.clear.cgColor;
layer.fillColor = UIColor.clear.cgColor;
self.view.layer.addSublayer(layer);
As a bonus almost all of CAShapeLayer's properties are animatable including lineDashPhase
which means you can make it look like the dashes are moving around the box.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With