利用AVFoundation实现二维码扫描以及其中的问题

来源:互联网 发布:js调用手机软键盘事件 编辑:程序博客网 时间:2024/06/07 00:33

来介绍以下我在封装二维码扫描工具时遇到的问题:

首先是网络上很常见的基本设置代码,还是很容易懂得

_captureDevice = [AVCaptureDevicedefaultDeviceWithMediaType:AVMediaTypeVideo];

    _captureInput = [AVCaptureDeviceInputdeviceInputWithDevice:_captureDeviceerror:nil];

    _metadataOutput = [[AVCaptureMetadataOutputalloc] init];

    [_metadataOutputsetMetadataObjectsDelegate:selfqueue:dispatch_get_main_queue()];

    _captureSession = [[AVCaptureSessionalloc] init];

    [_captureSessionsetSessionPreset:AVCaptureSessionPresetHigh];

    if ([_captureSessioncanAddInput:_captureInput]) {

        [_captureSessionaddInput:_captureInput];

    }

    if ([_captureSessioncanAddOutput:_metadataOutput]) {

        [_captureSessionaddOutput:_metadataOutput];

    }

    _metadataOutput.metadataObjectTypes =@[AVMetadataObjectTypeQRCode,AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code,AVMetadataObjectTypeCode128Code];

    _preview = [AVCaptureVideoPreviewLayerlayerWithSession:_captureSession];

    _preview.videoGravity =AVLayerVideoGravityResizeAspectFill;

    _preview.frame = controller.view.layer.bounds;

    [controller.view.layerinsertSublayer:_previewatIndex:0];

    [_captureSessionstartRunning];


代理方法中返回扫描结果:

- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection{


问题:

1.设置扫描有效区域,因为见到过的有扫描功能的软件都是中间一个区域扫描,所以我也来限制一下区域,也很容易的就知道要设置AVCaptureMetadataOutput的rectOfInterest属性,然后就是这个rect不是一般的rect是0-1的一个比例值,还需要x,y,width,height互相调换去设置等等,然后又看到有人说可以用metadataOutputRectOfInterestForRect去设置,然后就可以避免自己去各种转换过程中的问题,结果这样设置之后又发现扫描不成功了,发现是上面那个方法转换失败了,报了个error,但是我又不想就这样放弃了这个方法不用,就找到这个http://stackoverflow.com/questions/32401364/how-do-i-use-the-metadataoutputrectofinterestforrect-method-and-rectofinterest-p英文的帖子详细读了一遍,发现是需要在AVCaptureVideoPreviewLayer已经加载到页面并且摄像头已经启动扫描后才能设置,所以又加了一个通知,等加载完再设置,然后就成功了。

2.扫描的不够快。我相对比一下微信和支付宝的扫描速度,经过多次尝试后发现,微信速度好快,支付宝较慢。经过思考后发现,微信扫描经常是还没把二维码放进中间的框框,就已经扫描出来了,支付宝大概需要放到框内才行。那么很明显,微信是全屏都是扫描范围,也就是不设置rectOfInterest属性,支付宝应该是设置的。然后我就学习微信的方法不设置范围,发现效率果然很高,所以我觉得还是不设置的好,中间那个框框也有他的作用,不是说非得放到框里,而是在框里正中的话,扫描辨识度会高,也就是条形码有时候非得放中间才能成功的原因。


0 0
原创粉丝点击