如何使用贝塞尔曲线路径剪辑 UIView?

How to clip a UIView with a bezier path?

我不太确定理解 UIBezierPath 应该如何工作。

我在屏幕中间添加了一个简单的 UIView,我想通过在其图层中添加蒙版来剪辑它。我试过这个,以为我会在视图中间得到类似 losange 的东西:

override func viewDidLoad() {
    super.viewDidLoad()
    viewToClip.backgroundColor = .white
    let bezierPath = UIBezierPath()
    bezierPath.move(to: viewToClip.center)
    bezierPath.addLine(to: CGPoint(x: viewToClip.center.x - 5, y: viewToClip.center.y))
    bezierPath.addLine(to: CGPoint(x: viewToClip.center.x, y: viewToClip.center.y - 5))
    bezierPath.addLine(to: CGPoint(x: viewToClip.center.x + 5, y: viewToClip.center.y))
    bezierPath.addLine(to: CGPoint(x: viewToClip.center.x, y: viewToClip.center.y + 5))
    bezierPath.close()
    let testLayer = CAShapeLayer()
    testLayer.path = bezierPath.cgPath
    viewToClip.layer.mask = testLayer
}

但取而代之的是,视图只是从屏幕上消失了。我做错了什么?

感谢您的帮助。

你能试试吗

import UIKit

class bb: UIView {

   var once:Bool = true 

     override func draw(_ rect: CGRect) {

      if(once)
      {
        once = false
        self.backgroundColor = .white
        let bezierPath = UIBezierPath()
        let cen = CGPoint.init(x: self.bounds.size.width/2, y: self.bounds.size.height/2)
        bezierPath.move(to: cen)
        bezierPath.addLine(to: CGPoint(x: cen.x - 5, y: cen.y))
        bezierPath.addLine(to: CGPoint(x: cen.x, y: cen.y - 5))
        bezierPath.addLine(to: CGPoint(x: cen.x + 5, y: cen.y))
        bezierPath.addLine(to: CGPoint(x: cen.x, y: cen.y + 5))
        bezierPath.close()
        let testLayer = CAShapeLayer()
        testLayer.path = bezierPath.cgPath
        testLayer.lineWidth = 1.0

        testLayer.strokeColor = UIColor.blue.cgColor
        testLayer.fillColor = UIColor.green.cgColor
        self.layer.addSublayer(testLayer)
      }        

}