设置 UIView
的圆角半径可以通过以下方式完成:
设置
层
的cornerRadius
属性:view.layer.cornerRadius = 5; view.layer.masksToBounds = true;
敷面膜:
func roundCorners(corners:UIRectCorner, radius: CGFloat) { let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius)) let mask = CAShapeLayer() mask.path = path.cgPath self.layer.mask = mask }
覆盖
draw(_:)
:func draw(_ rect: CGRect) { // Size of rounded rectangle let rectWidth = rect.width let rectHeight = rect.height // Find center of actual frame to set rectangle in middle let xf: CGFloat = (self.frame.width - rectWidth) / 2 let yf: CGFloat = (self.frame.height - rectHeight) / 2 let ctx = UIGraphicsGetCurrentContext()! ctx.saveGState() let rect = CGRect(x: xf, y: yf, width: rectWidth, height: rectHeight) let clipPath = UIBezierPath(roundedRect: rect, cornerRadius: rectCornerRadius).cgPath ctx.addPath(clipPath) ctx.setFillColor(rectBgColor.cgColor) ctx.closePath() ctx.fillPath() ctx.restoreGState() }
以下哪一项通常被认为是在 UIView
上实现圆角的“正确”方法,考虑了以下标准:
- 配置(一些角可能是圆的,而另一些则不是)
- 动画(你能为
cornerRadius
变化做动画吗) - 灵 active (是否会破坏第三方库或您已经应用的掩码)
- 可读性(解决方案的简洁/可重用程度)
- 速度(是否对性能产生负面影响)
最佳答案
请注意,我不知道目前设置 UIView 的圆角半径的“正确”方法是什么。
我更喜欢做的是尽可能多地使用 Interface Builder 而无需额外的代码,这种方法显示了并且对我的经验来说是可靠的。
从 iOS 11 开始
您可以通过设置以下属性在Interface Builder
的Identity inspector
中使用用户定义的运行时属性:
layer.cornerRadius
layer.maskedCorners
layer.masksToBounds
根据documentation of the CACornerMask您可以看到 maskedCorners
属性实际上是一个 NSUInteger
数据类型,您可以设置以下值:
kCALayerMinXMinYCorner = 1U << 0
kCALayerMaxXMinYCorner = 1U << 1
kCALayerMinXMaxYCorner = 1U << 2
kCALayerMaxXMaxYCorner = 1U << 3
由于您可以对这些掩码进行按位或
,因此您只需“计算”您实际需要的按位或的结果整数。
因此,为 maskedCorners
属性设置以下数字(整数)值以获得圆角:
0 = no corner is being rounded
1 = top left corner rounded only
2 = top right corner rounded only
3 = top left and top right corners rounded only
4 = bottom left corner rounded only
5 = top left and bottom left corners rounded only
6 = top right and bottom left corners rounded only
7 = top left, top right and bottom left corners rounded only
8 = bottom right corner rounded only
9 = top left and bottom right corners rounded only
10 = top right and bottom right corners rounded only
11 = top left, top right and bottom right corners rounded only
12 = bottom left and bottom right corners rounded only
13 = top left, bottom left and bottom right corners rounded only
14 = top right, bottom left and bottom right corners rounded only
15 = all corners rounded
示例:如果您想为 UIView 的左上角和右上角设置角半径,您可以使用这些属性:
关于ios - 当前设置 UIView 的角半径的 "correct"方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44611878/