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