二维码扫描与生成

来源:互联网 时间:2017-01-22


一、扫描


1、 ZBar
ZBar在扫描的灵敏度上,和内存的使用上相对于ZXing上都是较优的,但是对于 “圆角二维码” 的扫描确很困难


2、ZXing
ZXing 是 Google Code上的一个开源的条形码扫描库,是用java设计的,连Google Glass 都在使用的。但有人为了追求更高效率以及可移植性,出现了c++ port. Github上的Objectivc-C port,其实就是用OC代码封装了一下而已,而且已经停止维护。这样效率非常低,在instrument下面可以看到CPU和内存疯涨,在内存小的机器上很容易崩溃。


3、AVFoundation
AVFoundation无论在扫描灵敏度和性能上来说都是最优的,所以毫无疑问我们应该切换到AVFoundation,需要兼容iOS 6或之前的版本可以用zbar或zxing代替。


代码如下:


 #import "PUCaptureCodeViewController.h"
#import <AVFoundation/AVFoundation.h>
@interface PUCaptureCodeViewController ()<AVCaptureMetadataOutputObjectsDelegate, UITabBarDelegate>
{
AVCaptureSession *session; //扫描会话
AVCaptureDeviceInput *deviceInput; //输入设备
AVCaptureMetadataOutput *metadataOutput; //输出设备
AVCaptureVideoPreviewLayer *previewLayer; //预览图层
}
@property (weak, nonatomic) IBOutlet UIImageView *edgeView; //边沿视图
@property (weak, nonatomic) IBOutlet UITabBar *tabBar;
@property (weak, nonatomic) IBOutlet UIImageView *slinderView; //冲击波视图
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *sacnLineTop; //冲击波视图与顶部的约束
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *scanBGViewHight;

@end

@implementation PUCaptureCodeViewController
- (void)viewDidLoad {
[super viewDidLoad];

}

- (void)viewDidAppear:(BOOL)animated{
[super viewDidAppear:animated];
[self layoutUI];
[self startAnimation];
[self startScan];
}

pragma mark private Methods
 - (void)layoutUI{
//设置默认的 tabBar
self.tabBar.selectedItem = self.tabBar.items[0];
UIImage *image = [UIImage imageNamed:@"[email protected]2x"];
image = [image resizableImageWithCapInsets:UIEdgeInsetsMake(image.size.height/2, image.size.width/2,image.size.height/2, image.size.width/2) resizingMode:UIImageResizingModeStretch];
self.edgesForExtendedLayout = UIRectEdgeNone;
self.edgeView.image = image;
//1、获取扫描会话
session = [[AVCaptureSession alloc]init];
//2. 获取到输入设备
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
if (device != nil) {
deviceInput = [[AVCaptureDeviceInput alloc]initWithDevice:device error:nil];
}else{
return;
}

//3、获取到输出设备
metadataOutput = [[AVCaptureMetadataOutput alloc]init];
//4、获取到预览图层
previewLayer = [[AVCaptureVideoPreviewLayer alloc]initWithSession:session];
previewLayer.frame = self.view.frame;
//5. 设置填充模式,不设置填充模式,4s可能会出现问题
previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;

}

//开始扫描


 - (void)startScan{
//1、判断是否支持输入设备
if(![session canAddInput:deviceInput]){
return;
}
//2、判断是否支持输出设备
if (![session canAddOutput:metadataOutput]) {
return;
}
//3、添加输入设备
[session addInput:deviceInput];
//4. 添加输出设备
[session addOutput:metadataOutput];
//5. 设置输出设备支持的类型,availableMetadataObjectTypes 为设备支持的所有类型
metadataOutput.metadataObjectTypes = metadataOutput.availableMetadataObjectTypes;
//6、设置代理,用于获取扫描的内容
[metadataOutput setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
//7、添加图层
[self.view.layer insertSublayer:previewLayer atIndex:0];
//8、开始扫描
[session startRunning];
}

- (void)startAnimation{
//设置起始位置
self.sacnLineTop.constant = -300;
//更新约束
[self.view layoutIfNeeded];
//设置动画
[UIView animateWithDuration:3.0 animations:^{
//设置重复次数
[UIView setAnimationRepeatCount:MAXFLOAT];
self.sacnLineTop.constant = self.view.frame.size.height;
[self.view layoutIfNeeded];
}];

}

pragma mark delegate Methods
 - (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection{
NSLog(@"%@", metadataObjects.lastObject);
// 1. 如果扫描完成,停止会话
[session stopRunning];
// 2. 删除预览图层
[previewLayer removeFromSuperlayer];
NSLog(@"%@", metadataObjects);
// 3. 设置界面显示扫描结果
if (metadataObjects.count > 0){
AVMetadataMachineReadableCodeObject *obj = metadataObjects[0];
// 提示:如果需要对url或者名片等信息进行扫描,可以在此进行扩展!
NSLog(@"%@", obj.stringValue);
}

}

- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item{
self.tabBar.selectedItem = item;
self.scanBGViewHight.constant = item.tag == 0 ? 300 : 300*0.5;
[self.view layoutIfNeeded];
//移除掉所有动画
[self.slinderView.layer removeAllAnimations];
//开始动画
[self startAnimation];

}

@end

二、生成二维码


1、生成二维码的步骤: 导入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];

2、生成二维码实例


- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.

self.imgView=[[UIImageView alloc]initWithFrame:CGRectMake(100, 100, [UIScreen mainScreen].bounds.size.width/2.0, [UIScreen mainScreen].bounds.size.width/2.0)];
[self.view addSubview:_imgView];
[self erweima];
}

pragma mark private Methods
 -(void)erweima
{
//二维码滤镜
CIFilter *filter=[CIFilter filterWithName:@"CIQRCodeGenerator"];
//恢复滤镜的默认属性
[filter setDefaults];
//将字符串转换成NSData
NSData *data=[@"www.baidu.com" dataUsingEncoding:NSUTF8StringEncoding];
//通过KVO设置滤镜inputmessage数据
[filter setValue:data forKey:@"inputMessage"];
//获得滤镜输出的图像
CIImage *outputImage=[filter outputImage];
//将CIImage转换成UIImage,并放大显示
_imgView.image=[self createNonInterpolatedUIImageFormCIImage:outputImage withSize:100.0];

//如果还想加上阴影,就在ImageView的Layer上使用下面代码添加阴影
_imgView.layer.shadowOffset=CGSizeMake(0, 0.5);//设置阴影的偏移量
_imgView.layer.shadowRadius=1;//设置阴影的半径
_imgView.layer.shadowColor=[UIColor blackColor].CGColor;//设置阴影的颜色为黑色
_imgView.layer.shadowOpacity=0.3;

}

//改变二维码大小


 - (UIImage *)createNonInterpolatedUIImageFormCIImage:(CIImage *)image withSize:(CGFloat) size {
CGRect extent = CGRectIntegral(image.extent);
CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
// 创建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);
// 保存bitmap到图片
CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
CGContextRelease(bitmapRef);
CGImageRelease(bitmapImage);
return [UIImage imageWithCGImage:scaledImage];
}



相关阅读:
Top