Search code examples
iosuibezierpath

How to clip a UIView with a bezier path?


I'm not totally sure to understand how UIBezierPath is supposed to work.

I have added a simple UIView in the middle of the screen, and I wanted to clip it by adding a mask to its layer. I tried this, thinking I'd get something like a losange in the middle of the view:

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
}

But instead of that, the view simply disappears from the screen. What am I doing wrong?

Thanks for your help.


Solution

  • Can you try

    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)
          }        
    
    }