2013-12-22 180 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