美文网首页
Swift 四个角设置不同半径大小的圆角

Swift 四个角设置不同半径大小的圆角

作者: jsone | 来源:发表于2021-12-22 17:33 被阅读0次
不同半径大小的圆角效果图

一、声明一个存储四个角的半径的结构体

struct YDRectCorner {
    var topLeft: CGFloat
    var topRight: CGFloat
    var bottomLeft: CGFloat
    var bottomRight: CGFloat
    // 创建四个角不同半径大小的圆角结构体
    init(topLeft: CGFloat = 0, topRight: CGFloat = 0, bottomLeft: CGFloat = 0, bottomRight: CGFloat = 0) {
        self.topLeft = topLeft
        self.topRight = topRight
        self.bottomLeft = bottomLeft
        self.bottomRight = bottomRight
    }
    // 创建四个角相同半径大小的圆角结构体
    init(all cornerRadius: CGFloat) {
        self.topLeft = cornerRadius
        self.topRight = cornerRadius
        self.bottomLeft = cornerRadius
        self.bottomRight = cornerRadius
    }
}

二、View扩张添加设置圆角的方法

func addCorner(_ corners: YDRectCorner, frame: CGRect? = nil) {
    let rect: CGRect = frame ?? self.bounds
    // 绘制路径
    let path = CGMutablePath()
    let topLeftRadius = corners.topLeft
    let topLeftCenter = CGPoint(x: rect.minX + topLeftRadius, y: rect.minY + topLeftRadius)
    path.addArc(center: topLeftCenter, radius: topLeftRadius, startAngle: Double.pi, endAngle: Double.pi * 1.5, clockwise: false)
    let topRightRadius = corners.topRight
    let topRightCenter = CGPoint(x: rect.maxX - topRightRadius, y: rect.minY + topRightRadius)
    path.addArc(center: topRightCenter, radius: topRightRadius, startAngle: Double.pi * 1.5, endAngle: Double.pi * 2, clockwise: false)
    let bottomRightRadius = max(corners.bottomRight, 0)
    let bottomRightCenter = CGPoint(x: rect.maxX - bottomRightRadius, y: rect.maxY - bottomRightRadius)
    path.addArc(center: bottomRightCenter, radius: bottomRightRadius, startAngle: 0, endAngle: Double.pi * 0.5, clockwise: false)
    let bottomLeftRadius = max(corners.bottomLeft, 0)
    let bottomLeftCenter = CGPoint(x: rect.minX + bottomLeftRadius, y: rect.maxY - bottomLeftRadius)
    path.addArc(center: bottomLeftCenter, radius: bottomLeftRadius, startAngle: Double.pi * 0.5, endAngle: Double.pi, clockwise: false)
    path.closeSubpath()
    // 给layer添加遮罩
    let layer = CAShapeLayer()
    layer.path = path
    self.layer.mask = layer
}

三、调用设置圆角的方法

1.四个角设置相同半径大小的圆角

cornerView.addCorner(YDRectCorner(all: 15))
相同半径大小的圆角

2.在指定frame四个角设置相同半径大小的圆角

cornerView.addCorner(YDRectCorner(all: 15), frame: CGRect(x: 10, y: 10, width: 50, height: 50))
指定`frame`四个角设置相同半径大小的圆角

2.四个角设置不同半径大小的圆角

cornerView.addCorner(YDRectCorner(topLeft: 10, topRight: 35, bottomRight: 80))
不同半径大小的圆角

参考文章:
Swift - UIView设置四个角不同圆角大小

相关文章

网友评论

      本文标题:Swift 四个角设置不同半径大小的圆角

      本文链接:https://www.haomeiwen.com/subject/dogqqrtx.html