How do I round only the top two corners of a UILab

2020-02-24 04:49发布

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.

3条回答
够拽才男人
2楼-- · 2020-02-24 05:01

I have checked the Class Reference for UIView & UILabel and its layers, but could not find any way to do this with the means given by the iOS.

You could do one thing, create a UIView & apply rounded corners to it. Now add a UILabel as a subview to this UIView & position it in such a way so that the bottom 2 rounded corners are covered by the label. This way you get the effect you need...

查看更多
做自己的国王
3楼-- · 2020-02-24 05:06

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
查看更多
乱世女痞
4楼-- · 2020-02-24 05:16

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

查看更多
登录 后发表回答