iOS開發(OC)——二維碼掃描(原生API,支援條形碼)
阿新 • • 發佈:2019-01-09
今天,我為大家介紹一下iOS原生API實現二維碼和條形碼掃描功能
主要程式碼如下
//獲取攝像裝置
AVCaptureDevice * device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
//建立輸入流
AVCaptureDeviceInput * input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
//建立輸出流
AVCaptureMetadataOutput * output = [[AVCaptureMetadataOutput alloc]init];
//設定代理 在主執行緒裡重新整理
[output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
//初始化連結物件
session = [[AVCaptureSession alloc]init];
//高質量採集率
[session setSessionPreset:AVCaptureSessionPresetHigh];
[session addInput:input];
[session addOutput:output];
//設定掃碼支援的編碼格式(如下設定條形碼和二維碼相容)
output.metadataObjectTypes[email protected][AVMetadataObjectTypeQRCode,AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code];
AVCaptureVideoPreviewLayer * layer = [AVCaptureVideoPreviewLayer layerWithSession:session];
layer.videoGravity=AVLayerVideoGravityResizeAspectFill;
layer.frame =self.layer.bounds;
[self.layer insertSublayer:layer atIndex:0];
//開始捕獲
[session startRunning];
//掃描的範圍
output.rectOfInterest=CGRectMake(0,0,1.0, 1.0);