创建扫描
关键代码如下:
//创建会话
self.session = [[AVCaptureSession alloc] init];
//获取摄像头设备
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaTy pe:AVMediaTypeVideo];
NSError *error = nil;
//创建输入流
AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error];
if(input) {
[self.session addInput:input];
} else {
//出错处理
NSLog(@"%@", error);
NSString *msg = [NSString stringWithFormat:@"请在手机【设置】-【隐私】-【相机】选项中,允许【%@】访问您的相机",[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleDisplayName"]];
UIAlertView *av = [[UIAlertView alloc]initWithTitle:@"提醒"
message:msg
delegate:self
cancelButtonTitle:@"OK"
otherButtonTitles: nil];
[av show];
return;
}
//创建输出流
AVCaptureMetadataOutput *output = [[AVCaptureMetadataOutput alloc] init];
[self.session addOutput:output];
//设置扫码类型
output.metadataObjectTypes = @[AVMetadataObjectTypeQRCo de, //条形码
AVMetadataObjectTypeEAN1 3Code,
AVMetadataObjectTypeEAN8 Code,
AVMetadataObjectTypeCode 128Code];
//设置代理,在主线程刷新
[output setMetadataObjectsDelega te:self queue:dispatch_get_main_queue()];
//创建摄像头取景区域
self.previewLayer = [AVCaptureVideoPreviewLay er layerWithSession:self.session];
self.previewLayer.videoGravity = AVLayerVideoGravityResiz eAspectFill;
[self.view.layer insertSublayer:self.previewLayer atIndex:0];
if ([self.previewLayer connection].isVideoOrientationSuppor ted)
[self.previewLayer connection].videoOrientation = AVCaptureVideoOrientatio nPortrait;
//开始扫码
[self.session startRunning];
2. 限制扫描区域
如图所示,非指定区域内不会识别,这样能够这样能够加快识别速度。
AVCaptureMetadataOutput *output;
output.rectOfInterest
关键是设置这个属性,但是很多坑,参考不少资料试了很多方法,原来是要在AVCaptureInputPortFormat
通知内设置才行。
__weak typeof(self) weakSelf = self;
[[NSNotificationCenter defaultCenter]addObserverForName:AVCaptureInputPortFormat DescriptionDidChangeNoti fication
object:nil
queue:[NSOperationQueue mainQueue]
usingBlock:^(NSNotification * _Nonnull note) {
if (weakSelf){
//调整扫描区域
AVCaptureMetadataOutput *output = weakSelf.session.outputs.firstObject;
output.rectOfInterest = [weakSelf.previewLayer metadataOutputRectOfInte restForRect:weakSelf.scanerView.scanAreaRect];
}