寫這篇文章的重點,其實不是示範如何用 AVFoundation 做二維碼掃描,而是解決一個更實際的問題——如何限制掃描的範圍。因為系統預設是全屏掃描,實務上常常需要把辨識區域縮小。
專案裡遇到掃描二維碼的需求時,我放棄了第三方庫,改用蘋果原生的方案。原生做法的優點很明顯:掃描速度快、效率高。但惱人的是,一開始完全找不到限制掃描範圍的方法。
先來看會用到的核心類別:
@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;
// Device
_device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
// Input
_input = [AVCaptureDeviceInput deviceInputWithDevice:self.device error:nil];
// Output
_output = [[AVCaptureMetadataOutput alloc] init];
[_output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
// Session
_session = [[AVCaptureSession alloc] init];
[_session setSessionPreset:AVCaptureSessionPresetHigh];
if ([_session canAddInput:self.input]) { [_session addInput:self.input]; }
if ([_session canAddOutput:self.output]) { [_session addOutput:self.output]; }
// 設定條碼類型為 QR Code
_output.metadataObjectTypes = @[AVMetadataObjectTypeQRCode];
// Preview
_preview = [AVCaptureVideoPreviewLayer layerWithSession:_session];
_preview.videoGravity = AVLayerVideoGravityResizeAspectFill;
_preview.frame = self.view.layer.bounds;
[self.view.layer insertSublayer:_preview atIndex:0];
// Start
[_session startRunning];
接著實作 AVCaptureMetadataOutputObjectsDelegate:
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
if ([metadataObjects count] > 0) {
[_session stopRunning];
AVMetadataMachineReadableCodeObject *metadataObject = [metadataObjects objectAtIndex:0];
NSString *stringValue = metadataObject.stringValue;
}
}
做到這裡,二維碼掃描已經能正常運作,但問題也浮現了:此時是全屏掃描。

官方文件的說明大意是:rectOfInterest 用來設定每一幀畫面中感興趣的區域,與其相交的 metadata 物件才會被回傳,預設值為 CGRectMake(0, 0, 1, 1)。看到這裡我大喜,以為只要把它設成中間框的 frame 就行:
[_output setRectOfInterest:CGRectMake((ScreenWidth-220)/2, 60+64, 220, 220)];
結果怎麼掃都掃不出來。仔細重讀文件才發現,區域原點在左上方,且數值是相對於裝置尺寸的比例,最大值為 1。於是我改成除以螢幕寬高:
[_output setRectOfInterest:CGRectMake(((ScreenWidth-220)/2)/ScreenWidth, (60+64)/ScreenHigh, 220/ScreenWidth, 220/ScreenHigh)];
但掃描結果依然偏差很大。不死心的我又設了一個確定的值來測試:
[_output setRectOfInterest:CGRectMake(0.5, 0.5, 0.5, 0.5)];
按理說這應該是右下方四分之一區域,沒想到掃出來卻是左下方!這才驚覺 rectOfInterest 的原點竟是在右上角。於是我猜測會不會是 X 與 Y 座標互換了,決定試試看:
[_output setRectOfInterest:CGRectMake((60+64)/ScreenHigh, ((ScreenWidth-220)/2)/ScreenWidth, 220/ScreenWidth, 220/ScreenHigh)];
這次原點終於對了!但寬高又對不上,難不成寬高也互換了?趕緊再試:
[_output setRectOfInterest:CGRectMake((124)/ScreenHigh, ((ScreenWidth-220)/2)/ScreenWidth, 220/ScreenHigh, 220/ScreenWidth)];
忐忑地再掃一次——完美!原來 rectOfInterest 的原點在右上角,而且寬高的 X、Y 也需要對調。折騰半天,系統原生掃描二維碼終於能精準限定範圍了。
今天就把這個踩坑經驗分享給大家,轉載請註明出處。 —— LC