Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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: Demo

Corner is wiped out.

like image 616
Shadi Ghelman Avatar asked Jun 17 '20 17:06

Shadi Ghelman


People also ask

How do you set corner radius for UIView in storyboard?

Select the view that you want to round and open its Identity Inspector. In the User Defined Runtime Attributes section, add the following two entries: Key Path: layer. cornerRadius , Type: Number, Value: (whatever radius you want)

How do you add a dashed border in UIView?

To use this, call the addDashedBorder() on your view. You can use the same extension on UILabel or almost any view. That's all on how to add dashed line border around UIView.

How do I change my corner radius to UIView?

If you start with a regular UIView it has square corners. You can give it round corners by changing the cornerRadius property of the view's layer . and smaller values give less rounded corners. Both clipsToBounds and masksToBounds are equivalent.

How do you make a view corner radius in Swift?

To make an image with round corners or to make any view or button or any UI element with round corners in swift, we need to access the corner radius property of its layer. Every UI element in iOS is based on a layer. First of all, let's add an UIImageView Object in our storyboard. Or let's create one programmatically.


1 Answers

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

like image 105
Mojtaba Hosseini Avatar answered Oct 10 '22 23:10

Mojtaba Hosseini