//获取信息输入设备
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
//创建输入流
AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:&err];
//创建输出流
AVCaptureMetadataOutput *output = [[AVCaptureMetadataOutput alloc] init];
[output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
AVCaptureSession *captureSeccion = [[AVCaptureSession alloc] init];
captureSeccion.sessionPreset = AVCaptureSessionPresetHigh;
if (!input) return;
[captureSeccion addInput:input];
[captureSeccion addOutput:output];
self.captureSession = captureSeccion;
output.metadataObjectTypes = @[AVMetadataObjectTypeQRCode,AVMetadataObjectTypeEAN13Code,AVMetadataObjectTypeEAN8Code,AVMetadataObjectTypeCode128Code];
AVCaptureVideoPreviewLayer *previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:self.captureSession];
previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
previewLayer.frame = self.scanView.bounds;
[self.captureSession startRunning];
CGRect interRect = [previewLayer metadataOutputRectOfInterestForRect:self.scanRect];
[self.scanView.layer insertSublayer:previewLayer atIndex:0];
output.rectOfInterest = interRect;
这里有个坑:
引用网友的一段话: AVCaptureMetadataOutput 中的属性rectOfInterest 看起来是CGRect类型, 结果让你填写一个比例, 当你填写比例是你会发现还是有各种问题, 最后总结一下, 加入你的屏幕的frame 为 x , y, w, h, 你要设置的矩形快的frame 为 x1, y1, w1, h1. 那么你的 rectOfInterest 应该设置为 CGRectMake(y1/y, x1/x, h1/h, w1/w)。
也可以向上面的代码一样,进行一次转换。