Ios – How to add overlay on AVCaptureVideoPreviewLayer

avcapturesessionavfoundationiosswift

I am building an iOS app using Swift which requires QR code scanner functionality.

I have implemented a QR code scanner using AVFoundation, right now my capture screen looks same as a video recording screen i.e. AVCaptureVideoPreviewLayer shows what is being captured by the camera.

But since it is a QR code scanner and not a regular image or video capture, I would like my VideoPreviewLayer to look like this:
camera overlay screenshot

I understand this can be achieved by adding another VideoPreviewLayer on top of one VideoPreviewLayer.

My questions are:

  1. How do I add the borders only to the edges in the upper (or smaller) preview layer?

  2. How do I change the brightness level for the VideoPreviewLayer in the background?

  3. How to ignore media captured by the the background layer?

Best Answer

You shouldn't use another VideoPreviewLayer. Instead you should add two sublayers - one for the masked background area and one for the corners.

Have a look at the source code in this repo for an example.

To limit the video capturing to the masked area you have to set the rectOfInterest of your AVCaptureMetadataOutput.

let rectOfInterest = videoPreviewLayer.metadataOutputRectConverted(fromLayerRect: rect)
metadataOutput.rectOfInterest = rectOfInterest