UIView+rounded.swift 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. //
  2. // UIView+rounded.swift
  3. // ADHTuanCan
  4. //
  5. // Created by 敖德亨 on 2023/11/2.
  6. //
  7. import Foundation
  8. import UIKit
  9. extension UIView{
  10. func addCorner(_ corners: YDRectCorner, frame: CGRect? = nil) {
  11. let rect: CGRect = frame ?? self.bounds
  12. // 绘制路径
  13. let path = CGMutablePath()
  14. let topLeftRadius = corners.topLeft
  15. let topLeftCenter = CGPoint(x: rect.minX + topLeftRadius, y: rect.minY + topLeftRadius)
  16. path.addArc(center: topLeftCenter, radius: topLeftRadius, startAngle: Double.pi, endAngle: Double.pi * 1.5, clockwise: false)
  17. let topRightRadius = corners.topRight
  18. let topRightCenter = CGPoint(x: rect.maxX - topRightRadius, y: rect.minY + topRightRadius)
  19. path.addArc(center: topRightCenter, radius: topRightRadius, startAngle: Double.pi * 1.5, endAngle: Double.pi * 2, clockwise: false)
  20. let bottomRightRadius = max(corners.bottomRight, 0)
  21. let bottomRightCenter = CGPoint(x: rect.maxX - bottomRightRadius, y: rect.maxY - bottomRightRadius)
  22. path.addArc(center: bottomRightCenter, radius: bottomRightRadius, startAngle: 0, endAngle: Double.pi * 0.5, clockwise: false)
  23. let bottomLeftRadius = max(corners.bottomLeft, 0)
  24. let bottomLeftCenter = CGPoint(x: rect.minX + bottomLeftRadius, y: rect.maxY - bottomLeftRadius)
  25. path.addArc(center: bottomLeftCenter, radius: bottomLeftRadius, startAngle: Double.pi * 0.5, endAngle: Double.pi, clockwise: false)
  26. path.closeSubpath()
  27. // 给layer添加遮罩
  28. let layer = CAShapeLayer()
  29. layer.path = path
  30. self.layer.mask = layer
  31. }
  32. }