#自從iOS7以后中新增了二維碼掃描功能。因此可以在不借助第三方類庫的情況下簡單的寫出二維碼的掃描功能;
原生的二維碼掃描功能在AVFoundation框架下,所以在使用原生的二維碼掃描功能時要先導入AVFoundation框架;
然后添加以下屬性:
<PRe><code>@property (strong,nonatomic) AVCaptureDevice *device;
@property (strong,nonatomic) AVCaptureDeviceInput *input;
@property (strong,nonatomic) AVCaptureMetadataOutput *output;
@property (strong,nonatomic) AVCapturesession *session;
@property (strong,nonatomic) AVCaptureVideoPreviewLayer *preview;</code></pre>
下面是對上面屬性的實例化:
self.device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo]; self.input = [AVCaptureDeviceInput deviceInputWithDevice:self.device error:nil]; self.output = [[AVCaptureMetadataOutput alloc] init]; [self.output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()]; self.session = [[AVCaptureSession alloc] init]; [self.session setSessionPreset:AVCaptureSessionPresetHigh]; if ([self.session canAddInput:self.input]) { [self.session addInput:self.input]; } if ([self.session canAddOutput:self.output]) { [self.session addOutput:self.output]; } // 掃碼類型 self.output.metadataObjectTypes = @[AVMetadataObjectTypeQRCode]; self.preview = [AVCaptureVideoPreviewLayer layerWithSession:self.session]; self.preview.videoGravity = AVLayerVideoGravityResizeaspectFill; self.preview.frame = self.view.layer.bounds; [self.view.layer insertSublayer:self.preview atIndex:0]; [self.session startRunning];
|
這兒是掃碼成功之后調用的代理方法 #pragma mark AVCaptureMetadataOutputObjectsDelegate - (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection { NSString *stringValue; if ([metadataObjects count] >0) { //停止掃描 [_session stopRunning]; AVMetadataMachineReadableCodeObject * metadataObject = [metadataObjects objectAtIndex:0]; stringValue = metadataObject.stringValue; } NSLog(@" %@",stringValue); // 獲取到二維碼的數據之后的后續操作 } |
以上代碼基本上可以實現掃碼的功能了。但是怎么樣才能實現規定區域內的掃碼呢?這就需要用到之間創建的屬性 output ;output有一個屬性
output.rectOfInterest 專門用來設置可掃碼的區域;
設置AVCaptureMetadataOutput的rectOfInterest的屬性,即可掃描區域:
這樣設置就可以:output.rectOfInterest = CGRectMake(y的起點/屏幕的高,x的起點/屏幕的寬,掃描的區域的高/屏幕的高,掃描的區域的寬/屏幕的寬);
掃描動畫的實現:不在多說
新聞熱點
疑難解答