QRScanner BarCodeScanner 二维码条形码扫描
iOS二维码条形码扫描,支持iOS7+,限制扫描区域,提升扫描速度ios
GitHub看了很多,找了些,发现没几个满意的,因而本身整理了一下。 从新写了个demo demo_iOS7+git
关键代码以下:github
//建立会话 self.session = [[AVCaptureSession alloc] init]; //获取摄像头设备 AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType: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 = @[AVMetadataObjectTypeQRCode, //条形码 AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code]; //设置代理,在主线程刷新 [output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()]; //建立摄像头取景区域 self.previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:self.session]; self.previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill; [self.view.layer insertSublayer:self.previewLayer atIndex:0]; if ([self.previewLayer connection].isVideoOrientationSupported) [self.previewLayer connection].videoOrientation = AVCaptureVideoOrientationPortrait; //开始扫码 [self.session startRunning];
如图所示,非指定区域内不会识别,这样可以这样可以加快识别速度。session
AVCaptureMetadataOutput *output; output.rectOfInterest
关键是设置这个属性,可是不少坑,参考很多资料试了不少方法,原来是要在AVCaptureInputPortFormatDescriptionDidChangeNotification
通知内设置才行。ide
__weak typeof(self) weakSelf = self; [[NSNotificationCenter defaultCenter]addObserverForName:AVCaptureInputPortFormatDescriptionDidChangeNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) { if (weakSelf){ //调整扫描区域 AVCaptureMetadataOutput *output = weakSelf.session.outputs.firstObject; output.rectOfInterest = [weakSelf.previewLayer metadataOutputRectOfInterestForRect:weakSelf.scanerView.scanAreaRect]; } }];
参考(感谢)博文资料:
IOS7使用原生API进行二维码和条形码的扫描
iOS 原生二维码扫描(可限制扫描区域)
IOS二维码扫描,你须要注意的两件事
iOS 原生扫 QR 码的那些事ui
下载demo_iOS7+spa