如今二維碼隨處可見,無論是實體商品還是各式禮券都少不了它的身影,而手機等行動裝置更成為二維碼的理想應用平台。本文就從「生成二維碼」與「掃描二維碼」兩個方向切入,帶大家快速掌握這項實用功能。
一、生成二維碼
二維碼可以存放純文字、名片或 URL。生成步驟如下:導入 CoreImage 框架,透過 CIFilter 濾鏡產生二維碼,過程包含建立過濾器、還原預設屬性、設定內容、取得輸出圖像、顯示二維碼。
// 1. 建立過濾器 CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"]; // 2. 還原濾鏡預設屬性 [filter setDefaults]; // 3. 設定內容 NSString *str = @"這是一個二維碼的生成結果"; NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding]; [filter setValue:data forKey:@"inputMessage"]; // 使用 KVO 設定屬性 // 4. 取得輸出圖像 CIImage *outputImage = [filter outputImage]; // 5. 顯示二維碼 self.imageView.image = [UIImage imageWithCIImage:outputImage];
如此顯示的圖片往往不夠清晰,可以自行重繪以產生高畫質版本:
- (UIImage *)createNonInterpolatedUIImageFormCIImage:(CIImage *)image withSize:(CGFloat)size {
CGRect extent = CGRectIntegral(image.extent);
CGFloat scale = MIN(size / CGRectGetWidth(extent), size / CGRectGetHeight(extent));
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);
CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
CGContextRelease(bitmapRef);
CGImageRelease(bitmapImage);
return [UIImage imageWithCGImage:scaledImage];
}
小提醒:當內容設為網址時,若帶有協議頭(如 https://),掃描後會自動開啟網頁。
二、掃描二維碼(AVFoundation 框架)
掃描流程可歸納為:建立捕捉會話 AVCaptureSession、加入輸入設備(相機輸入 AVCaptureDeviceInput)、加入元數據輸出 AVCaptureMetadataOutput 並設定類型、加入預覽圖層 AVCaptureVideoPreviewLayer、啟動掃描,最後在回呼代理中取得結果。
#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 設定元數據類型為二維碼
[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];
}
- (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
總結一句:二維碼的實作其實並不難,掌握生成與掃描的關鍵步驟,即可靈活應用於各種情境。