我知道在iOS 3.0+中我可以使用
label.layer.cornerRadius = xxx;
如何将UILabel的四个角(作为UIView子类)都变成圆角,但我只想要圆角在标签的顶部两个角,并保持底部角直角呢?
是否有方法可以在UILabel中实现此功能?其他解决方案通常假设您使用自定义UIView而不是UILabel。
label.layer.cornerRadius = xxx;
如何将UILabel的四个角(作为UIView子类)都变成圆角,但我只想要圆角在标签的顶部两个角,并保持底部角直角呢?
是否有方法可以在UILabel中实现此功能?其他解决方案通常假设您使用自定义UIView而不是UILabel。
我想贴出包含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
您可以使用CALayers和遮罩来实现此目的。
CAShapeLayer *maskLayer = [CAShapeLayer layer];
maskLayer.path = maskPath.CGPath;
label.layer.mask = maskLayer;
其中maskPath是使用bezierPathWithRoundedRect:byRoundingCorners:cornerRadii
设置的UIBezierPath。
我已经查看了UIView和UILabel的类参考以及它们的层,但是在iOS提供的手段中找不到任何方法来实现这一点。
你可以做一件事情,创建一个UIView
并将其应用于圆角。现在将一个UILabel
作为子视图添加到此UIView中,并以这样的方式定位它,以便标签覆盖底部2个圆角。这样你就可以得到你需要的效果...