详解iOS7原生二维码,条码扫描

来源:互联网 发布:怎么开发java手机游戏 编辑:程序博客网 时间:2024/05/01 17:42

Demo点这https://github.com/JLHuu/ScanQRCode.git

在需要适配iOS6的时代过去后,可以不再用zxing来做二维码扫描了,AVFoundation库中,iOS7后的原生二维码扫描效率上会较以前的三方库提高很多。

首先介绍这几个类:

    AVCaptureDevice *_device; // 设备

    AVCaptureDeviceInput *_input;//设备输入

    AVCaptureMetadataOutput *_output;//输出

    AVCaptureSession *_session; // 链接

    AVCaptureVideoPreviewLayer *_preview;//展示

这几个类就可以构成二维码、条码的扫描。大家一看就明白了,贴代码

// 视频设备    _device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];    // torchMode 闪光灯状态,需要先调用lockForConfiguration:    //    [_device lockForConfiguration:nil];    //    if ([_device isTorchModeSupported:AVCaptureTorchModeOn]) {    //        _device.torchMode = AVCaptureTorchModeOn;    //    }        _input = [AVCaptureDeviceInput deviceInputWithDevice:_device error:nil];    _output = [[AVCaptureMetadataOutput alloc] init];    // rectOfInterest AVCaptureMetadataOutput的属性,可以设置扫描区域,范围是rect 0~1,这个范围是相对于设备尺寸来说的,这里也就是相对于AVCaptureVideoPreviewLayer的尺寸来说的。注意:此处有坑,rect的属性是反的(x,y互换,w,h互换),具体请看http://www.tuicool.com/articles/6jUjmur    _output.rectOfInterest = CGRectMake(.5-(200/SCREEN_HEIGHT)/2.f,.5-(200/SCREEN_WIDTH)/2.f, 200/SCREEN_HEIGHT ,200/SCREEN_WIDTH);    // 设置输出代理    dispatch_queue_t serialqueue = dispatch_queue_create("serialqueue", DISPATCH_QUEUE_SERIAL);    [_output setMetadataObjectsDelegate:self queue:serialqueue];    _session = [[AVCaptureSession alloc] init];    if ([_session canAddInput:_input]) {        [_session addInput:_input];    }    if ([_session canAddOutput:_output]) {        [_session addOutput:_output];    }        // MetadataObjectTypes的设置一定要在session add output后设置,否者运行会crash    /*     二维码扫描用AVMetadataObjectTypeQRCode     条码扫描用AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code     关于同时能扫描二维码和条码的效率问题,请看http://www.cocoachina.com/industry/20140530/8615.html     */    //    [_output setMetadataObjectTypes:[NSArray arrayWithObjects:AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code, nil]];    [_output setMetadataObjectTypes:@[AVMetadataObjectTypeQRCode]];    _preview = [AVCaptureVideoPreviewLayer layerWithSession:_session];    // AVCaptureVideoPreviewLayer的尺寸决定输入源在video上的尺寸,如果frame放缩,则video也会相应放缩。    _preview.frame = self.view.bounds;    // A string defining how the video is displayed within an AVCaptureVideoPreviewLayer bounds rect.    // 一个字符串用来定义video怎样在AVCaptureVideoPreviewLayer的尺寸下展示    _preview.videoGravity = AVLayerVideoGravityResizeAspect;    [self.view.layer addSublayer:_preview];

做完这些事,其实已经可以进行扫描了,rectOfInterest这个属性是设置扫描区域的,里面有坑,具体看Demo里面的注释。最后加些扫描框框,动画什么的就大功告成了。注意条码和二维码在一块扫描会有效率的问题具体可以看看这篇文章http://www.cocoachina.com/industry/20140530/8615.html


Demo下载


0 0