Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create rounded corners with CAShapeLayer

Is there a way to add rounded corners to a CAShapeLayer? In my case I needed the shape layer to create a dashed border via lineDashPattern.

Rounded corners with dashed line - incorrect

^ notice how the dashed line is not rounded

like image 712
David James Avatar asked Mar 12 '14 15:03

David James


People also ask

How can you created rounded corners?

To create a rounded corner, we use the CSS border-radius property. This property is used to set the border-radius of element.

How do you round one corner in Swift?

If you want only some corners to be rounded, you should set the layer's maskedCorners property to be an array of the corners you want – it's an option set, so you can set one or many depending on your needs.


1 Answers

The answer is simple. Create a bézier path with rounded corners.

UPDATE for Swift

view.clipsToBounds = true 
view.layer.cornerRadius = 10.0
let border = CAShapeLayer()
border.path = UIBezierPath(roundedRect:view.bounds, cornerRadius:10.0).cgPath
border.frame = view.bounds
border.fillColor = nil 
border.strokeColor = UIColor.purple.cgColor
border.lineWidth = borderWidth * 2.0 // doubled since half will be clipped
border.lineDashPattern = [15.0]
view.layer.addSublayer(border)

Objective-C

// (This old code assumes this is within a view with a custom property "border".)
self.clipsToBounds = YES; 
self.layer.cornerRadius = 10.0;

self.border = [CAShapeLayer layer];
self.border.fillColor = nil;
self.border.path = [UIBezierPath bezierPathWithRoundedRect:self.bounds cornerRadius:10.0].cgPath;
self.border.frame = self.bounds;
    
self.border.strokeColor = [UIColor purpleColor].CGColor;
self.border.lineWidth = borderWidth * 2; // double desired width as half will be clipped
self.border.lineDashPattern = @[@15];

[self.layer addSublayer:self.border];

Rounded corners with dashed line - correct

like image 155
David James Avatar answered Oct 22 '22 16:10

David James