利用AVFoundation實現二維碼掃描以及其中的問題

來介紹以下我在封裝二維碼掃描工具時遇到的問題:

首先是網絡上很常見的基本設置代碼,還是很容易懂得

_captureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];

    _captureInput = [AVCaptureDeviceInput deviceInputWithDevice:_captureDevice error:nil];

    _metadataOutput = [[AVCaptureMetadataOutput alloc] init];

    [_metadataOutput setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];

    _captureSession = [[AVCaptureSession alloc] init];

    [_captureSession setSessionPreset:AVCaptureSessionPresetHigh];

    if ([_captureSession canAddInput:_captureInput]) {

        [_captureSession addInput:_captureInput];

    }

    if ([_captureSession canAddOutput:_metadataOutput]) {

        [_captureSession addOutput:_metadataOutput];

    }

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

    _preview = [AVCaptureVideoPreviewLayer layerWithSession:_captureSession];

    _preview.videoGravity = AVLayerVideoGravityResizeAspectFill;

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

    [controller.view.layer insertSublayer:_preview atIndex:0];

    [_captureSession startRunning];


代理方法中返回掃描結果:

- (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屬性,支付寶應該是設置的。然後我就學習微信的方法不設置範圍,發現效率果然很高,所以我覺得還是不設置的好,中間那個框框也有他的作用,不是說非得放到框裏,而是在框里正中的話,掃描辨識度會高,也就是條形碼有時候非得放中間才能成功的原因。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章