2013-12-22 133 views
5

我目前正在AVCaptureSessionAVCaptureMetadataOutput工作。AVCaptureSession条码扫描

它完美,但我只是想知道如何指示扫描并仅在AVCaptureVideoPreviewLayer的特定区域进行分析的元数据对象?

回答

13

下面是从项目的代码示例我可以帮助您在正确的轨道上

// 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]; 
+1

一个项目:HTTPS://github.com/jpwidmer/iOS7-BarcodeScanner –

+1

对于这样:[previewLayer metadataOutputRectOfInterestForRect:previewLayer.bounds]时,结果是:{{楠,楠},{楠,楠}} –

+0

注意,previewLayer.frame的边界来自self.previewView.bounds(这是一些先前实例化的UIView)。您应该检查,这UIView的(如:您正在使用此代码之前,自动布局定义您的self.previewView ??的大小),在这一点上有一定的限度 –

2

在iOS系统9.3.2我有“CGAffineTransformInvert:奇异矩阵”,呼吁metadataoutputRectOfInterestForRect时错误。我能使其工作在调用它之后startRunning方法AVCaptureSession

captureSession.startRunning() 
let visibleRect = previewLayer.metadataOutputRectOfInterestForRect(previewLayer.bounds) 
captureMetadataOutput.rectOfInterest = visibleRect