title: How to cut portion of CALayer in iOS Swift?
body: <p>I am trying to create a QR Reader. For that I am showing a rectOfInterest with some CALayer for visual representation. I want to show a box with some border at the corners and black background with some opacity so hide the other view from the <code>AVCaptureVideoPreviewLayer</code>. What I have achieved till now looks like this:</p>
  
  <p><a href="https://i.stack.imgur.com/75ZaQ.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/75ZaQ.jpg" alt="Screenshot"></a></p>
  
  <p>As you can see the CALayer is there but I want to cut the box portion of the layer so that that blackish thing does not come there. The code I am using to do this is like below:</p>
  
  <pre><code>func createTransparentLayer()-&gt;CALayer{
          let shape = CALayer()
          shape.frame = self.scanView.layer.bounds
          shape.backgroundColor = UIColor.black.cgColor
          shape.opacity = 0.7
          return shape
      }
  </code></pre>
  
  <p>I looked into other questions for this, seems like you have the <strong>mask</strong> the layer with the cut portion. So I subclassed the CALayer and <strong>cleared the context</strong> in <strong>drawInContext</strong> and set the <code>mask</code> property of the super layer to this. After that I get <strong>nothing</strong>. Everything is invisible there. What is wrong in this?</p>
  
  <p>The code I tried is this:</p>
  
  <pre><code>class TransparentLayer: CALayer {
      override func draw(in ctx: CGContext) {
          self.backgroundColor = UIColor.black.cgColor
          self.opacity = 0.7
          self.isOpaque = true
          ctx.clear(CGRect(x: superlayer!.frame.size.width / 2 - 100, y: superlayer!.frame.size.height / 2 - 100, width: 200, height: 200))
      }
  }
  </code></pre>
  
  <p>then set the mask property like this:</p>
  
  <pre><code>override func viewDidLayoutSubviews() {
          self.rectOfInterest = CGRect(x: self.scanView.layer.frame.size.width / 2 - 100, y: self.scanView.layer.frame.size.height / 2 - 100, width: 200, height: 200)
          scanView.rectOfInterest = self.rectOfInterest
          let shapeLayer = self.createFrame()
          scanView.doInitialSetup()
          self.scanView.layer.mask = self.createTransparentLayer()
          self.scanView.layer.addSublayer(shapeLayer)
      }
  </code></pre>
  
  <p>here the <code>shapeLayer</code> is the bordered corner in the screenshot. How can I achieve this?</p>