简体   繁体   中英

How add corner radius to dashed border around an UIView

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: 演示

Corner is wiped out.

Quick Answer

You should round the Layer s 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)

演示

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM