AVCaptureSession 条码扫描

7

我目前正在使用 AVCaptureSessionAVCaptureMetadataOutput 进行工作。

它的功能非常完美,但我想知道如何指示仅在 AVCaptureVideoPreviewLayer 的特定区域扫描和分析元数据对象?

2个回答

14

这是我一个项目中的示例代码,希望能帮助你找到正确的方向。

    // 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
对于这个代码:[previewLayer metadataOutputRectOfInterestForRect:previewLayer.bounds],结果是:{{nan, nan}, {nan, nan}}。 - Seb Thiebaud
请注意,previewLayer.frame的边界来自于self.previewView.bounds(这是先前实例化的某个UIView)。您应该检查此时此UIView是否具有边界(例如,您是否在自动布局定义了self.previewView的大小之前使用了此代码?) - So Over It

4
在iOS 9.3.2中,当调用metadataoutputRectOfInterestForRect时,我遇到了“CGAffineTransformInvert:singular matrix”错误。我成功解决了这个问题,在AVCaptureSessionstartRunning方法后立即调用它。
captureSession.startRunning()
let visibleRect = previewLayer.metadataOutputRectOfInterestForRect(previewLayer.bounds)
captureMetadataOutput.rectOfInterest = visibleRect

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接