在iOS7下扫描二维码

NSError *error;
AVCaptureDevice *captureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:captureDevice error:&error];

if (error)
{
    NSLog(@"%@", [error domain]);
    return;
}

self.captureSession = [[AVCaptureSession alloc] init];
[self.captureSession addInput:input];

AVCaptureMetadataOutput *captureMetadataOutput = [[AVCaptureMetadataOutput alloc] init];
[self.captureSession addOutput:captureMetadataOutput];
    
[captureMetadataOutput setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
[captureMetadataOutput setMetadataObjectTypes:@[AVMetadataObjectTypeQRCode]];

AVCaptureVideoPreviewLayer *layer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.captureSession];
[layer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
[layer setFrame:self.view.layer.bounds];
[self.view.layer addSublayer:layer];
self.videoPreviewLayer = layer;

[self.captureSession startRunning];

一切顺利,扫描的效率很高。

可出现了一个问题,我只想在屏幕中的小框内扫描,而不是整个屏幕都可以扫描,类似于微信的效果。

查看文档后发现AVCaptureMetadataOutput类有一个属性rectOfInterest。

rectOfInterest的默认值是CGRectMake(0,0,1,1)

0和1是相对于屏幕的比例,而不是具体的数值。

而且x和y,width和height的位置都互换了。

添加代码:

CGRect lensRect = self.lensView.frame;

CGFloat screenW = ScreenSize.width;
CGFloat screenH = ScreenSize.height;
CGRect rectInterest = CGRectMake(CGRectGetMinY(lensRect) / screenH,
                                 ((screenW-CGRectGetWidth(lensRect)))/2/screenW,
                                 CGRectGetHeight(lensRect) / screenH,
                                 CGRectGetWidth(lensRect) / screenW);

[captureMetadataOutput setRectOfInterest:rectInterest];

大功告成!

你可能感兴趣的:(在iOS7下扫描二维码)