Reputation: 193
I want to set border on UIButton and rounded corners ONLY in one side
I use this code:
//set rounded corners on top
UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.scanButton.bounds byRoundingCorners:(UIRectCornerTopLeft | UIRectCornerTopRight) cornerRadii:CGSizeMake(10.0, 10.0)];
CAShapeLayer *maskLayer = [CAShapeLayer layer];
maskLayer.frame = self.scanButton.bounds;
maskLayer.path = maskPath.CGPath;
self.scanButton.layer.mask = maskLayer;
// set border
self.scanButton.layer.borderColor = [UIColor blackColor].CGColor;
self.scanButton.layer.borderWidth = 2.0f;
[self.scanButton.layer setMasksToBounds:YES];
How can I make proper border in top corners?
Upvotes: 2
Views: 4913
Reputation: 1964
The corners of your border are clipping because you've probably set the background color of your view on the UIView itself. A better way to do this would just be to set the fill color directly on your layer. This could be done like this:
let button = ... // your existing UIButton
let borderLayer = CAShapeLayer()
borderLayer.strokeColor = UIColor.blackColor().CGColor
borderLayer.fillColor = UIColor.yellowColor().CGColor
borderLayer.borderWidth = 2.0
let borderPath = UIBezierPath(roundedRect: button.bounds,
byRoundingCorners: [.TopLeft, .TopRight],
cornerRadii: CGSize(width:10.0, height: 10.0))
borderLayer.path = borderPath.CGPath
button.layer.insertSublayer(borderLayer, atIndex: 0)
The above would give you this result without clipped corners:
I've put together a UIButton subclass using this method where the border radius can be set on each corner of the button individually, check it out here: https://gist.github.com/alexpls/95279b3f9a2da7f2d7bf, hopefully it helps!
Upvotes: 7
Reputation: 5694
Take a look at following answer - Stroke masked CALayer in iOS He using combination of mask & shape layer to draw such custom border. You will need to turn off a regular border for masked layer.
Upvotes: 1
Reputation: 1474
you're probably better off subclassing UIButton and overriding drawRect: with your custom drawing. you need to implement a CGContext and add your UIBezierPath then stroke it. Can't recall if you need to make it a CGPath first, but i don't think so.
Upvotes: 2