Search code examples
swiftcore-graphicsuibezierpath

Dashed line with rounded corners


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:

enter image description here

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
    }
}

Solution

  • 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.