7

I'm currently working with AVCaptureSession and AVCaptureMetadataOutput.

It works perfectly, but I just want to know how to indicate to scan and analyze metadata objects only on a specific region of the AVCaptureVideoPreviewLayer?

harpun
  • 4,022
  • 1
  • 36
  • 40
Seb Thiebaud
  • 2,419
  • 1
  • 15
  • 13

2 Answers2

14

Here is a sample of code from a project I have that may help you on the right track

    // where 'self.session' is previously setup  AVCaptureSession

    // setup metadata capture
    AVCaptureMetadataOutput *metadataOutput = [[AVCaptureMetadataOutput alloc] init];
    [self.session addOutput:metadataOutput];
    [metadataOutput setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    [metadataOutput setMetadataObjectTypes:@[AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeEAN13Code]];

    // setup preview layer
    AVCaptureVideoPreviewLayer *previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.session];
    previewLayer.frame = self.previewView.bounds;
    previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;

    // we only want the visible area of the previewLayer to accept
    // barcode input (ignore the rest)
    // we need to convert rects coordinate system
    CGRect visibleMetadataOutputRect = [previewLayer metadataOutputRectOfInterestForRect:previewLayer.bounds];
    metadataOutput.rectOfInterest = visibleMetadataOutputRect;

    // add the previewLayer as a sublayer of the displaying UIView
    [self.previewView.layer addSublayer:previewLayer];
So Over It
  • 3,668
  • 3
  • 35
  • 46
  • 1
    For this: [previewLayer metadataOutputRectOfInterestForRect:previewLayer.bounds], the result is: {{nan, nan}, {nan, nan}} – Seb Thiebaud Dec 23 '13 at 19:30
  • Note that the bounds of the previewLayer.frame comes from self.previewView.bounds (which is some previously instantiated UIView). You should check that this UIView has bounds at this point (eg. are you using this code before auto layout has defined the size of your self.previewView??) – So Over It Jan 03 '14 at 14:39
4

In iOS 9.3.2 I had "CGAffineTransformInvert: singular matrix" error when calling metadataoutputRectOfInterestForRect. I was able to make it work calling it right after startRunning method of AVCaptureSession:

captureSession.startRunning()
let visibleRect = previewLayer.metadataOutputRectOfInterestForRect(previewLayer.bounds)
captureMetadataOutput.rectOfInterest = visibleRect
Avt
  • 16,927
  • 4
  • 52
  • 72