如何仅使UILabel的顶部两个角四舍五入?

6
我知道在iOS 3.0+中我可以使用

 label.layer.cornerRadius = xxx;

如何将UILabel的四个角(作为UIView子类)都变成圆角,但我只想要圆角在标签的顶部两个角,并保持底部角直角呢?

是否有方法可以在UILabel中实现此功能?其他解决方案通常假设您使用自定义UIView而不是UILabel。

3个回答

29

我想贴出包含BezierPath的完整代码。

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;

对于 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

16

您可以使用CALayers和遮罩来实现此目的。

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

其中maskPath是使用bezierPathWithRoundedRect:byRoundingCorners:cornerRadii设置的UIBezierPath。


我认为应该是 label.layer.mask = maskLayer。 - Anand
我接受了这个答案,因为我不想在这里使用额外的视图。我使用两个覆盖层,底部层全部圆角,而顶部层只有顶部两个角是圆角的。达到这种效果:http://icons.iconarchive.com/icons/walrick/openphone/256/Calendar-icon.png - Anand

1

我已经查看了UIView和UILabel的类参考以及它们的层,但是在iOS提供的手段中找不到任何方法来实现这一点。

你可以做一件事情,创建一个UIView并将其应用于圆角。现在将一个UILabel作为子视图添加到此UIView中,并以这样的方式定位它,以便标签覆盖底部2个圆角。这样你就可以得到你需要的效果...


确保UIView和UILabel具有相同的颜色。 - chatur

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接