我正在尝试使用以下代码使顶角变圆
func roundCorners(corners:UIRectCorner, radius: CGFloat) {
let path = UIBezierPath(roundedRect: self.bounds,
byRoundingCorners: corners,
cornerRadii: CGSize(width: radius, height: radius))
let maskLayer = CAShapeLayer()
maskLayer.frame = self.bounds
maskLayer.path = path.cgPath
self.layer.mask = maskLayer
}
使用
myView.roundCorners(corners:[.topLeft, .topRight], radius: radius)
这是在 tableView sectionHeader 中,如果我向下滚动然后使用相同的代码将其四舍五入:
并且顶部折扣视图角也使用相同的功能进行倒圆角。
谢谢你的帮助。
更新 如果我固定视图的宽度那么它工作正常。
iOS 11 引入了 maskedCorners,可以产生更平滑、质量更好的结果。您仍然可以在函数调用中使用 UIRectCorner 并将其转换为 CACornerMask:
斯威夫特 5:
extension UIView {
func roundCorners(_ corners: UIRectCorner, radius: CGFloat) {
if #available(iOS 11.0, *) {
clipsToBounds = true
layer.cornerRadius = radius
layer.maskedCorners = CACornerMask(rawValue: corners.rawValue)
} else {
let path = UIBezierPath(
roundedRect: bounds,
byRoundingCorners: corners,
cornerRadii: CGSize(width: radius, height: radius)
)
let mask = CAShapeLayer()
mask.path = path.cgPath
layer.mask = mask
}
}
}
在@Paolo 的帮助下解决了这个问题,下面是工作代码。
斯威夫特 3.2
extension UIView {
func roundCorners(corners:UIRectCorner, radius: CGFloat) {
DispatchQueue.main.async {
let path = UIBezierPath(roundedRect: self.bounds,
byRoundingCorners: corners,
cornerRadii: CGSize(width: radius, height: radius))
let maskLayer = CAShapeLayer()
maskLayer.frame = self.bounds
maskLayer.path = path.cgPath
self.layer.mask = maskLayer
}
}
}
为了调用此函数,请使用下面的行并提及您要圆化的角
self.myView.roundCorners(corners: [.topLeft, .topRight, .bottomLeft, .bottomRight], radius: 8.0)
也可以这样做
extension UIView {
func roundCorners(_ corners: UIRectCorner, radius: CGFloat) {
if #available(iOS 11.0, *) {
clipsToBounds = true
layer.cornerRadius = radius
corners.forEach { corner in
layer.maskedCorners = CACornerMask(rawValue: corner.rawValue)
}
} else {
corners.forEach { corner in
let path = UIBezierPath(
roundedRect: bounds,
byRoundingCorners: corner,
cornerRadii: CGSize(width: radius, height: radius)
)
let mask = CAShapeLayer()
mask.path = path.cgPath
layer.mask = mask
}
}
}
}
可以用作
yourView.roundCorners(.topLeft, .topRight, radius: 8)