我怎样才能围绕一个UILabel的顶部两个angular落?

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

label.layer.cornerRadius = xxx; 

将UILabel的所有四个angular(作为UIView子类)四舍五入,但是我只想围绕标签的顶部两个angular,并保持底angular直angular。

有什么办法可以用UILabel做到这一点? 其他解决scheme假定一个自定义的UIView,而不是一个UILabel。

你可以使用CALayers和掩码来做到这一点

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

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

以为我会张贴包含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 

我已经检查了UIView&UILabel及其图层的类参考,但是找不到用iOS提供的方法来做到这一点的方法。

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