Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I round only the top two corners of a 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 UIView subclass), but I want to round only the top two corners of the label and keep the bottom corners right-angled.

Is there any way I can do that with a UILabel? Other solutions assume a custom UIView, not a UILabel.

like image 592
Anand Avatar asked Jan 27 '12 14:01

Anand


2 Answers

Thought I would post the full code with the BezierPath included.

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
like image 51
digidigo Avatar answered Nov 15 '22 06:11

digidigo


You can do this using CALayers and masks

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

where maskPath is a UIBezierPath set up using bezierPathWithRoundedRect:byRoundingCorners:cornerRadii

like image 30
wattson12 Avatar answered Nov 15 '22 08:11

wattson12