二維碼已經是現代生活的常態風景,從商品包裝、電子票券到門店櫃檯,幾乎無所不在。手機作為最普及的行動載體,自然是掃碼與生碼最合適的平台。本文就分成「產生」與「掃描」兩條主線,把 iOS 上的實作路徑梳理清楚。
二維碼的內容可以是純文字、名片資訊(vCard)或一個網址。iOS 系統本身內建了 CIQRCodeGenerator 這個濾鏡,不必引入任何第三方庫就能完成編碼。
實作步驟:
// 二維碼的產生 // 1. 建立過濾器 CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"]; // 2. 還原濾鏡預設屬性 [filter setDefaults]; // 3. 設定要編碼的內容(必須是 NSData) NSString *str = @"這是一個二維碼的產生結果"; NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding]; [filter setValue:data forKey:@"inputMessage"]; // 4. 取得輸出結果 CIImage *outputImage = [filter outputImage]; // 5. 顯示 self.imageView.image = [UIImage imageWithCIImage:outputImage];
CIQRCodeGenerator 輸出的原始影像尺寸很小,直接貼到畫面上會出現明顯的鋸齒與模糊。解法是自己建立一張放大後的 bitmap,並關閉插值運算,讓每個色塊保持銳利邊緣。
/**
* 依 CIImage 產生指定尺寸的 UIImage
* @param image CIImage 物件
* @param size 目標寬高
*/
- (UIImage *)createNonInterpolatedUIImageFormCIImage:(CIImage *)image withSize:(CGFloat)size {
CGRect extent = CGRectIntegral(image.extent);
CGFloat scale = MIN(size / CGRectGetWidth(extent), size / CGRectGetHeight(extent));
// 1. 建立 bitmap 上下文
size_t width = CGRectGetWidth(extent) * scale;
size_t height = CGRectGetHeight(extent) * scale;
CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs,
(CGBitmapInfo)kCGImageAlphaNone);
CIContext *context = [CIContext contextWithOptions:nil];
CGImageRef bitmapImage = [context createCGImage:image fromRect:extent];
// 關掉插值,放大後才不會糊
CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
CGContextScaleCTM(bitmapRef, scale, scale);
CGContextDrawImage(bitmapRef, extent, bitmapImage);
// 2. 輸出成 UIImage
CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
CGContextRelease(bitmapRef);
CGImageRelease(bitmapImage);
CGColorSpaceRelease(cs);
return [UIImage imageWithCGImage:scaledImage];
}
另外有個實用小細節:如果編碼內容是網址,務必把協議頭(例如 https:// 或 https://)一起寫進去,掃描端才會辨識為可點擊的連結。
NSString *str = @"https://www.baidu.com"; // 缺少協議頭會被當成純文字
從 iOS 7 開始,AVFoundation 就提供了 metadata 讀取的完整能力,不必再依賴 ZBar、ZXing 這類外部庫。整體流程可以拆成五個環節:
#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>
@interface ViewController () <AVCaptureMetadataOutputObjectsDelegate>
@property (nonatomic, strong) AVCaptureVideoPreviewLayer *layer;
@property (nonatomic, strong) AVCaptureSession *session;
@end
@implementation ViewController
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
// 1. 建立捕捉工作階段
AVCaptureSession *session = [[AVCaptureSession alloc] init];
self.session = session;
// 2. 加入輸入裝置(相機)
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
[session addInput:input];
// 3. 加入輸出物件並設定代理
AVCaptureMetadataOutput *output = [[AVCaptureMetadataOutput alloc] init];
[output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
[session addOutput:output];
// 3.1 只辨識 QR Code 這一種碼
[output setMetadataObjectTypes:@[AVMetadataObjectTypeQRCode]];
// 4. 加上預覽圖層
AVCaptureVideoPreviewLayer *layer = [AVCaptureVideoPreviewLayer layerWithSession:session];
layer.frame = self.view.bounds;
[self.view.layer addSublayer:layer];
self.layer = layer;
// 5. 啟動
[session startRunning];
}
#pragma mark - 掃描結果回呼
- (void)captureOutput:(AVCaptureOutput *)captureOutput
didOutputMetadataObjects:(NSArray *)metadataObjects
fromConnection:(AVCaptureConnection *)connection {
if (metadataObjects.count > 0) {
AVMetadataMachineReadableCodeObject *object = [metadataObjects lastObject];
NSLog(@"掃描結果:%@", object.stringValue);
// 讀到就立即停止,避免持續耗電
[self.session stopRunning];
[self.layer removeFromSuperlayer];
} else {
NSLog(@"沒有掃描到資料");
}
}
@end
實務上還記得在 App 的 Info.plist 補上 NSCameraUsageDescription 的用途說明字串,並處理使用者拒絕相機權限的情況,否則在 iOS 10 之後會直接閃退。
總結一句:二維碼這件事,系統 API 已經把重活都做完了,剩下的只是把流程串起來而已。