1、为什么使用二维码?
在手机客户端应用里,对二维码的使用也比较多。常见的功能有物品信息查询,登录信息验证,扫描登录,扫描支付等。但是为什么使用它呢?
*二维码包含更多的信息量
*二维码采用了高密度编码
*编码范围广。二维码可以把图片、声音、文字、签字、指纹等可以数字化的信息进行编码,用条码表示出来;可以表示多种语言文字;可表示图像数据
*二维码译码准确。我们知道二维码只是一个图形,想要获取图形中的内容就需要对图形进行译码。二维码的译码误码率为千万分之一,而普通条形码的译码误码率的百分之二要低很多。
*安全。能够引入加密措施,与条形码相比,二维码的保密性更好。通过在二维码中引入加密措施,更好的保护译码内容不被他人获得。
因为二维码的这些特点,在项目里用到它的地方也会比较多。
2、怎么生成二维码?
导入CoreImage框架,通过滤镜CIFilter生成二维码
二维码的内容(传统的条形码只能放数字):纯文本,名片,URL
// 1. 实例化二维码滤镜
CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
// 2. 恢复滤镜的默认属性
[filter setDefaults];
// 3. 将字符串转换成
NSData NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
// 4. 通过KVO设置滤镜inputMessage数据
[filter setValue:data forKey:@"inputMessage"];
// 5. 获得滤镜输出的图像
CIImage *outputImage = [filter outputImage];
// 6. 将CIImage转换成UIImage,并放大显示
return [UIImage imageWithCIImage:outputImage scale:20.0 orientation:UIImageOrientationUp];
3、扫描二维码
扫描二维码就要用到系统设备,摄像头。这就要导入AVFoundation类库,并遵守AVCaptureMetadataOutputObjectsDelegate协议
这里会用到 AVCaptureDevice 捕捉用的设备、AVCaptureDeviceInput 输入通道、AVCaptureSession 对采集到的信息的处理与传输、AVCaptureMetadataOutput输出通道这几个的对象属性,当然还需要一张预览视图,为了显示正在进行扫描,还会添加动画效果。就是我们常见的一个上下刷动的网格线或者亮度条,其实它与采集信息无关。
#import "QRCodeVC.h"
#import <AVFoundation/AVFoundation.h>
@interface QRCodeVC ( )<AVCaptureMetadataOutputObjectsDelegate>
@property (nonatomic, strong) AVCaptureDevice *device;//扑捉用的设备
@property (nonatomic, strong) AVCaptureSession *session;//采集到的信息的处理与传输
@property (nonatomic, strong) AVCaptureMetadataOutput *output;//输出通道
@property (nonatomic, strong)UIView *preview;//预览视图
@property (nonatomic, strong)UIImageView *inamationView;//动画View
@property (nonatomic, strong) NSTimer *timer;//刷新动画的View
@end
接下来就是对扫描界面的搭建和程序处理,代码符上如下:
@implementation QRCodeVC
- (void)viewDidLoad {
[super viewDidLoad];
[self innationQRCode];
//设置UI效果
//添加矩形边框
UIImage *image = [UIImage imageNamed:@"qrcode_border"];
//拉伸矩形
image = [image resizableImageWithCapInsets:UIEdgeInsetsMake(25, 25, 26, 26)];
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, [[UIScreen mainScreen] bounds].size.width - 80, [[UIScreen mainScreen] bounds].size.width - 80)];
[imageView setImage:image];
CGPoint point = self.view.center;
point.y += -50;
imageView.center = point;
[self.view addSubview:imageView];
//剪切掉超出区域的动画
imageView.clipsToBounds = YES;
//动画效果
UIImageView *anamiView = [[UIImageView alloc] initWithFrame:imageView.bounds];
anamiView.image = [UIImage imageNamed:@"qrcode_scanline_qrcode"];
[imageView addSubview:anamiView];
self.inamationView = anamiView;
self.timer = [NSTimer scheduledTimerWithTimeInterval:0.01f target:self selector:@selector(changeInamation) userInfo:nil repeats:YES];
}
-(void)changeInamation{
//改变动画
self.inamationView.frame = CGRectOffset(self.inamationView.frame, 0, 2);
if (self.inamationView.frame.origin.y >= self.inamationView.frame.size.height) {
self.inamationView.frame = CGRectOffset(self.inamationView.bounds, 0, -self.inamationView.frame.size.height);
}
}
-(void)viewDidAppear:(BOOL)animated{
[super viewDidAppear:animated];
//开启二维码扫描,扑捉信息
[self start];
}
-(void)viewWillDisappear:(BOOL)animated{
[super viewWillDisappear:animated];
//停止二维码扫描
[self end];
}
//初始化配置
-(void)innationQRCode{
//获取设备
self.device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
//生成Input
NSError *error;
self.input = [AVCaptureDeviceInput deviceInputWithDevice:self.device error:&error];
if (error) {
NSLog(@"%@", error);
return;
}
//初始化session并且把input添加到session
self.session = [[AVCaptureSession alloc] init];
if ([self.session canAddInput:self.input]) {
[self.session addInput:self.input];
}
//初始化output
AVCaptureMetadataOutput *output = [[AVCaptureMetadataOutput alloc] init];
//设置�delegate
dispatch_queue_t queue;
queue = dispatch_queue_create("muQueue", NULL);//串行队列
[output setMetadataObjectsDelegate:self queue:queue];
self.output = output;
//把output添加到session中
[self.session addOutput:self.output];
//配置输出的数据类型,支持所有的数据类型
[self.output setMetadataObjectTypes:self.output.availableMetadataObjectTypes];
//设置预览图层,将session中扑捉的画面预览
AVCaptureVideoPreviewLayer *videoLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.session];
[videoLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
[videoLayer setFrame:self.view.frame];
//初始化预览视图
self.preview = [[UIView alloc] initWithFrame:self.view.bounds];
[self.view addSubview:self.preview];
[self.preview.layer addSublayer:videoLayer];
}
- (IBAction)cancel:(id)sender { //取消扫描
[self dismissViewControllerAnimated:YES completion:nil];
}
-(void)start{
[self.session startRunning];
[self.timer fire];
}
-(void)end{
[self.session stopRunning];
[self.timer invalidate];
}
-(void)result:(NSString *)str{
//得到结果,停止扫描,如果是网页,打开网页,如果是字符串,展示字符串
[self.session stopRunning];
UIViewController *vc = [self.storyboard instantiateViewControllerWithIdentifier:@"resultVC"];
[vc setValue:str forKey:@"result"];
if (self.navigationController.viewControllers.count > 1) {
return;
}
[self.navigationController pushViewController:vc animated:YES];
}
#pragma avcapture
-(void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection{
id object = metadataObjects.firstObject;
//只关心机器识别码
if ([object isKindOfClass:[AVMetadataMachineReadableCodeObject class]]) {
AVMetadataMachineReadableCodeObject *obj = (AVMetadataMachineReadableCodeObject *)object;
NSLog(@"%@", obj);
[self performSelectorOnMainThread:@selector(result:) withObject:obj.stringValue waitUntilDone:NO];
}
}
@end
若有错误,欢迎大家指出。有好的方式或代码,欢迎大家给我留言,吾将感激涕零,哈哈。