Search code examples
iosswiftavfoundationavcapture

AVCapture arbitrary shaped lens


Starting to handle the camera in a swift app I have the following chunk of code (which I got from the net) working as supposed to.

previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
self.view.layer.addSublayer(previewLayer!)
previewLayer?.frame = self.view.layer.frame
captureSession.startRunning()

I now want to modify it, so I can decide the shape of my lens, at this point it is a standard rectangle.

I have to be able to use an ellipse, a star, a polygon … or whatever.

I presume I should work on previewLayer but I am not even sure of that and more important I don’t really know how to do.


Solution

  • In case this may be useful to someone else, I post here the solution I found, taking the case of an ellipse.

    previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
    self.view.layer.addSublayer(previewLayer!)
    previewLayer?.frame = self.view.layer.frame
    
    let maskLayer = CAShapeLayer()
    maskLayer.path = CGPathCreateWithEllipseInRect(CGRect(x: 50.0, y: 100.0, width: 200.0, height: 100.0), nil)
    previewLayer!.mask = maskLayer
    
    captureSession.startRunning()