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];
一切順利膊毁,掃描的效率很高柬赐。
可出現(xiàn)了一個問題柒啤,我只想在屏幕中的小框內(nèi)掃描,而不是整個屏幕都可以掃描帽氓,類似于微信的效果。
查看文檔后發(fā)現(xiàn)AVCaptureMetadataOutput類有一個屬性rectOfInterest东亦。
rectOfInterest的默認值是CGRectMake(0,0,1,1)
0和1是相對于屏幕的比例杏节,而不是具體的數(shù)值。
而且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];
大功告成镊逝!