从@nont 中汲取灵感并使用扩展,我编写了这个 sn-p:
extension UIView {
public enum Corner: Int {
case TopRight
case TopLeft
case BottomRight
case BottomLeft
case All
}
public func blendCorner(corner corner: Corner, length: CGFloat = 20.0) {
let maskLayer = CAShapeLayer()
var path: CGPathRef?
switch corner {
case .All:
path = self.makeAnglePathWithRect(self.bounds, topLeftSize: length, topRightSize: length, bottomLeftSize: length, bottomRightSize: length)
case .TopRight:
path = self.makeAnglePathWithRect(self.bounds, topLeftSize: 0.0, topRightSize: length, bottomLeftSize: 0.0, bottomRightSize: 0.0)
case .TopLeft:
path = self.makeAnglePathWithRect(self.bounds, topLeftSize: length, topRightSize: 0.0, bottomLeftSize: 0.0, bottomRightSize: 0.0)
case .BottomRight:
path = self.makeAnglePathWithRect(self.bounds, topLeftSize: 0.0, topRightSize: 0.0, bottomLeftSize: 0.0, bottomRightSize: length)
case .BottomLeft:
path = self.makeAnglePathWithRect(self.bounds, topLeftSize: 0.0, topRightSize: 0.0, bottomLeftSize: length, bottomRightSize: 0.0)
}
maskLayer.path = path
self.layer.mask = maskLayer
}
private func makeAnglePathWithRect(rect: CGRect, topLeftSize tl: CGFloat, topRightSize tr: CGFloat, bottomLeftSize bl: CGFloat, bottomRightSize br: CGFloat) -> CGPathRef {
var points = [CGPoint]()
points.append(CGPointMake(rect.origin.x + tl, rect.origin.y))
points.append(CGPointMake(rect.origin.x + rect.size.width - tr, rect.origin.y))
points.append(CGPointMake(rect.origin.x + rect.size.width, rect.origin.y + tr))
points.append(CGPointMake(rect.origin.x + rect.size.width, rect.origin.y + rect.size.height - br))
points.append(CGPointMake(rect.origin.x + rect.size.width - br, rect.origin.y + rect.size.height))
points.append(CGPointMake(rect.origin.x + bl, rect.origin.y + rect.size.height))
points.append(CGPointMake(rect.origin.x, rect.origin.y + rect.size.height - bl))
points.append(CGPointMake(rect.origin.x, rect.origin.y + tl))
let path = CGPathCreateMutable()
CGPathMoveToPoint(path, nil, points.first!.x, points.first!.y)
for point in points {
if point != points.first {
CGPathAddLineToPoint(path, nil, point.x, point.y)
}
}
CGPathAddLineToPoint(path, nil, points.first!.x, points.first!.y)
return path
}
}
这样你可以轻松地融合你的角落:
let view = UIView()
view.blendCorner(corner: .TopRight)
// or view.blendCorner(corner: .All)