【发布时间】:2012-01-27 14:00:11
【问题描述】:
我知道在 iOS 3.0+ 中我可以使用
label.layer.cornerRadius = xxx;
圆 UILabel 的所有四个角(作为 UIView 子类),但我只想圆化标签的顶部两个角并保持底部角成直角。
有什么方法可以用 UILabel 做到这一点?其他解决方案假定使用自定义 UIView,而不是 UILabel。
【问题讨论】:
标签: iphone objective-c ios uilabel
我知道在 iOS 3.0+ 中我可以使用
label.layer.cornerRadius = xxx;
圆 UILabel 的所有四个角(作为 UIView 子类),但我只想圆化标签的顶部两个角并保持底部角成直角。
有什么方法可以用 UILabel 做到这一点?其他解决方案假定使用自定义 UIView,而不是 UILabel。
【问题讨论】:
标签: iphone objective-c ios 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 个圆角被标签覆盖。这样你就可以得到你需要的效果...
【讨论】: