【生成二维码】
iOS7以后苹果有CoreImage框架用于生成二维码,二维码通过滤镜生成,二维码滤镜可以将字符串转化为二维码。
注意字符串必须转化为NSData传入,通过KVC告诉滤镜。
滤镜输出为CIImage,注意要转化为UIImage使用。
代码如下:
// 1.实例化二维码滤镜 CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"]; // 2.重置滤镜属性 [filter setDefaults]; // 3.字符串转NSData NSData *data = [@"http://www.soulghost.com" dataUsingEncoding:NSUTF8StringEncoding]; // 4.通过KVC设置属性 [filter setValue:data forKey:@"inputMessage"]; // 5.生成二维码 CIImage *QRImage = [filter outputImage]; UIImage *image = [UIImage imageWithCIImage:QRImage];
【扫描二维码】
扫描二维码通过输入源摄像头、会话转换数据、输出成字符串完成二维码的解析。
代码如下:
// // ViewController.m // 读取二维码 // // Created by 11 on 8/3/15. // Copyright (c) 2015 soulghost. All rights reserved. // #import "ViewController.h" #import <AVFoundation/AVFoundation.h> @interface ViewController () <AVCaptureMetadataOutputObjectsDelegate> @property (nonatomic, strong) AVCaptureSession *session; @property (nonatomic, strong) AVCaptureVideoPreviewLayer *previewLayer; @end @implementation ViewController - (void)viewDidLoad{ [super viewDidLoad]; // 摄像头作为输入源 AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo]; AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil]; // 摄像头的输出转化为字符串作为输出源 AVCaptureMetadataOutput *output = [[AVCaptureMetadataOutput alloc] init]; [output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()]; // 实例化一个会话,它将摄像头采集的图像(input)转换成字符串(output)。 AVCaptureSession *session = [[AVCaptureSession alloc] init]; [session addInput:input]; [session addOutput:output]; _session = session; // 设置输出类型为二维码 [output setMetadataObjectTypes:@[AVMetadataObjectTypeQRCode]]; // 创建二维码的扫描视图,通过session判断显示的内容。 AVCaptureVideoPreviewLayer *preview = [AVCaptureVideoPreviewLayer layerWithSession:_session]; preview.videoGravity = AVLayerVideoGravityResizeAspectFill; preview.frame = self.view.bounds; [self.view.layer insertSublayer:preview atIndex:100]; _previewLayer = preview; // 开启会话 [_session startRunning]; } - (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection{ // 停止会话,移除扫描视图 [_session stopRunning]; [_previewLayer removeFromSuperlayer]; // 取出数据 if (metadataObjects.count > 0) { AVMetadataMachineReadableCodeObject *obj = [metadataObjects firstObject]; NSLog(@"%@",obj); } } @end