How add corner radius to dashed border around an UIView
Asked Answered
U

1

9

I have a rounded UIView and I have added a dashed line stroke to it.

,,,
    var view = CAShapeLayer()
    view.strokeColor = UIColor.red.cgColor
    view.lineDashPattern = [2, 2]
    view.frame = addphotoView.bounds
    view.fillColor = nil
    view.path = UIBezierPath(rect: addphotoView.bounds).cgPath
    view.cornerRadius = 16
    view.masksToBounds = true

    addphotoView.layer.addSublayer(yourViewBorder)

But view.cornerRadius is not working as expected: Demo

Corner is wiped out.

Unconditional answered 17/6, 2020 at 17:19 Comment(3)
I have updated your code and image due to visual issues (that I had with the preview image)Iconoclast
Oh. Thank you. I will remember that to be more careful.Unconditional
Please try this: stackoverflow.com/questions/78365576/custom-dashed-border-viewGentianaceous
I
27

Quick Answer

You should round the Layers path.

like this:

borderLayer.path = UIBezierPath(roundedRect: addphotoView.bounds, byRoundingCorners: .allCorners, cornerRadii: CGSize(width: 16, height: 16)).cgPath


Better Answer Using An Extension

You can move all this logic into an extension:

extension UIView {
    @discardableResult
    func addLineDashedStroke(pattern: [NSNumber]?, radius: CGFloat, color: CGColor) -> CALayer {
        let borderLayer = CAShapeLayer()

        borderLayer.strokeColor = color
        borderLayer.lineDashPattern = pattern
        borderLayer.frame = bounds
        borderLayer.fillColor = nil
        borderLayer.path = UIBezierPath(roundedRect: bounds, byRoundingCorners: .allCorners, cornerRadii: CGSize(width: radius, height: radius)).cgPath

        layer.addSublayer(borderLayer)
        return borderLayer
    }
}

Usage:

addphotoView.addLineDashedStroke(pattern: [2, 2], radius: 16, color: UIColor.gray.cgColor)

Demo

Iconoclast answered 17/6, 2020 at 17:20 Comment(3)
I have tried your answer and in my case, I have two views in the horizontal stack so dotted line goes out from the view horizontally. Any idea?Inessential
You should update the layer somewhere like layoutSubviewsIconoclast
Thanks for the extension! Can we somehow avoid the dashed lines touching at the start and end of the path? Its visible in your example view screenshot as well next to the top left corner.Hysteric

© 2022 - 2024 — McMap. All rights reserved.