How to combine only two upper corners of UILabel?

I know that in iOS 3.0+ I can use

 label.layer.cornerRadius = xxx;

to round all four corners of a UILabel (as a subclass of UIView), but I want to round only the top two corners of the label and keep the bottom corners at right angles.

Is there any way to do this using UILabel? Other solutions involve a custom UIView rather than a UILabel.

+4
source share
3 answers

You can do this with CALayers and mask

CAShapeLayer *maskLayer = [CAShapeLayer layer];
maskLayer.path = maskPath.CGPath;
label.layer.mask = maskLayer;

where maskPath is the UIBezierPath configured with bezierPathWithRoundedRect:byRoundingCorners:cornerRadii

+16
source

I think I would post the full code with BezierPath enabled.

CGRect bounds = label.bounds;
UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:bounds
                                                                   byRoundingCorners:(UIRectCornerTopLeft | UIRectCornerTopRight)
                                                                         cornerRadii:CGSizeMake(5.0, 5.0)];

CAShapeLayer *maskLayer = [CAShapeLayer layer];
maskLayer.frame = bounds;
maskLayer.path = maskPath.CGPath;

label.layer.mask = maskLayer;

For Swift 4.0:

let bounds: CGRect = label.bounds
let maskPath = UIBezierPath(roundedRect: bounds, byRoundingCorners: ([.topLeft, .topRight]), cornerRadii: CGSize(width: 5.0, height: 5.0))
let maskLayer = CAShapeLayer()
maskLayer.frame = bounds
maskLayer.path = maskPath.cgPath
label.layer.mask = maskLayer
+25
source

Reference UIView UILabel , , iOS.

You can do one thing, create UIViewand apply rounded corners to it. Now add UILabelas a subroutine to this UIView and place it so that the bottom 2 rounded corners are covered with a label. Thus, you will get the desired effect ...

+1
source

All Articles