AVCaptureSession
// 获取摄像设备
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
// 创建输入流
AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
if (!input) return;
// 创建输出流
AVCaptureMetadataOutput *output = [[AVCaptureMetadataOutput alloc] init];
// 设置代理 在主线程里刷新
[output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
// 设置有效扫描区域
CGRect scanCrop = [self getScanCrop:_scanView.bounds readerViewBounds:self.view.frame];
output.rectOfInterest = scanCrop;
// 初始化链接对象
// 提示:这里方便的话可以创建一个AVCaptureSession对象
_session = [[AVCaptureSession alloc] init];
// 高质量采集率
[_session setSessionPreset:AVCaptureSessionPresetHigh];
if ([_session canAddInput:input]) {
[_session addInput:input];
}
if ([_session canAddOutput:output]) {
[_session addOutput:output];
}
// 设置扫码支持的编码格式(如下设置条形码和二维码兼容)
output.metadataObjectTypes = @[AVMetadataObjectTypeQRCode,AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code];
AVCaptureVideoPreviewLayer *layer = [AVCaptureVideoPreviewLayer layerWithSession:_session];
layer.videoGravity = AVLayerVideoGravityResizeAspectFill;
layer.frame = self.view.layer.bounds;
[self.view.layer insertSublayer:layer atIndex:0];
// 开始捕获
[_session startRunning];
获取扫描区域的方法
// 获取扫描区域的比例关系
- (CGRect)getScanCrop:(CGRect)rect readerViewBounds:(CGRect)readerViewBounds {
CGFloat x, y, width, height;
x = (CGRectGetHeight(readerViewBounds) - CGRectGetHeight(rect)) / 2 / CGRectGetHeight(readerViewBounds);
y = (CGRectGetWidth(readerViewBounds) - CGRectGetWidth(rect)) / 2 /CGRectGetWidth(readerViewBounds);
width = CGRectGetHeight(rect) / CGRectGetHeight(readerViewBounds);
height = CGRectGetWidth(rect) / CGRectGetWidth(readerViewBounds);
return CGRectMake(x, y, width, height);
}
获取扫描结果的代理方法
// 必须服从AVCaptureMetadataOutputObjectsDelegate
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection {
if (metadataObjects.count > 0) {
[_session stopRunning]; // 停止扫描
AVMetadataMachineReadableCodeObject *metadataObject = [metadataObjects objectAtIndex:0];
NSLog(@"metadataObject.stringValue == %@", metadataObject.stringValue);
}
}