在Sanjay出色的回答基础上,我编写了一个快速的CALayer扩展程序,适用于Swift 2.3,以防您需要多次执行“仅圆角化某些角落”的操作。
extension CALayer {
func roundCorners(corners: UIRectCorner, radius: CGFloat) {
let maskPath = UIBezierPath(roundedRect: bounds,
byRoundingCorners: corners,
cornerRadii: CGSize(width: radius, height: radius))
let shape = CAShapeLayer()
shape.path = maskPath.CGPath
mask = shape
}
}
使用方法:
myView.layer.roundCorners([.TopLeft, .TopRight], radius: myCornerRadius)
Swift 3.0(在此示例中,边界来自于视图而非图层。使用视图的边界可以使这段代码适用于UITableViewCell中的视图。):
func roundCorners(corners: UIRectCorner, radius: CGFloat, viewBounds: CGRect) {
let maskPath = UIBezierPath(roundedRect: viewBounds,
byRoundingCorners: corners,
cornerRadii: CGSize(width: radius, height: radius))
let shape = CAShapeLayer()
shape.path = maskPath.cgPath
mask = shape
}
用法:
myView.layer.roundCorners(corners: [.topLeft, .topRight], radius: myCornerRadius, viewBounds: bounds)
bezierPathWithRoundedRect:byRoundingCorners:cornerRadii:
该方法是UIBezierPath
类的一个类方法,用于创建一个带有圆角的矩形路径。它需要四个参数:矩形的大小、要圆角的角落、以及每个角落的半径。 - matt