一、掃描
1济似、? ZBar
ZBar在掃描的靈敏度上矫废,和內(nèi)存的使用上相對于ZXing上都是較優(yōu)的,但是對于 “圓角二維碼” 的掃描確很困難
2砰蠢、ZXing
ZXing 是 Google Code上的一個開源的條形碼掃描庫蓖扑,是用java設(shè)計的,連Google Glass 都在使用的台舱。但有人為了追求更高效率以及可移植性律杠,出現(xiàn)了c++ port. Github上的Objectivc-C port,其實就是用OC代碼封裝了一下而已竞惋,而且已經(jīng)停止維護(hù)柜去。這樣效率非常低,在instrument下面可以看到CPU和內(nèi)存瘋漲拆宛,在內(nèi)存小的機(jī)器上很容易崩潰嗓奢。
3、AVFoundation
AVFoundation無論在掃描靈敏度和性能上來說都是最優(yōu)的浑厚,所以毫無疑問我們應(yīng)該切換到AVFoundation股耽,需要兼容iOS 6或之前的版本可以用zbar或zxing代替。
代碼如下:
#import "PUCaptureCodeViewController.h"? ? #import@interface PUCaptureCodeViewController (){
AVCaptureSession *session;? //掃描會話
AVCaptureDeviceInput *deviceInput;? //輸入設(shè)備
AVCaptureMetadataOutput *metadataOutput; //輸出設(shè)備
AVCaptureVideoPreviewLayer *previewLayer;? //預(yù)覽圖層
}
@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{
//設(shè)置默認(rèn)的 tabBar
self.tabBar.selectedItem = self.tabBar.items[0];
UIImage *image = [UIImage imageNamed:@"qrcode_border@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. 獲取到輸入設(shè)備
AVCaptureDevice? *device? = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
if (device != nil) {
deviceInput = [[AVCaptureDeviceInput alloc]initWithDevice:device error:nil];
}else{
return;
}
//3物蝙、獲取到輸出設(shè)備
metadataOutput = [[AVCaptureMetadataOutput alloc]init];
//4、獲取到預(yù)覽圖層
previewLayer = [[AVCaptureVideoPreviewLayer alloc]initWithSession:session];
previewLayer.frame = self.view.frame;
//5. 設(shè)置填充模式,不設(shè)置填充模式敢艰,4s可能會出現(xiàn)問題
previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
}
//開始掃描
- (void)startScan{
//1诬乞、判斷是否支持輸入設(shè)備
if(![session canAddInput:deviceInput]){
return;
}
//2、判斷是否支持輸出設(shè)備
if (![session canAddOutput:metadataOutput]) {
return;
}
//3、添加輸入設(shè)備
[session addInput:deviceInput];
//4. 添加輸出設(shè)備
[session addOutput:metadataOutput];
//5. 設(shè)置輸出設(shè)備支持的類型,availableMetadataObjectTypes 為設(shè)備支持的所有類型
metadataOutput.metadataObjectTypes = metadataOutput.availableMetadataObjectTypes;
//6丽惭、設(shè)置代理击奶,用于獲取掃描的內(nèi)容
[metadataOutput setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
//7辈双、添加圖層
[self.view.layer insertSublayer:previewLayer atIndex:0];
//8责掏、開始掃描
[session startRunning];
}
- (void)startAnimation{
//設(shè)置起始位置
self.sacnLineTop.constant = -300;
//更新約束
[self.view layoutIfNeeded];
//設(shè)置動畫
[UIView animateWithDuration:3.0 animations:^{
//設(shè)置重復(fù)次數(shù)
[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. 刪除預(yù)覽圖層
[previewLayer removeFromSuperlayer];
NSLog(@"%@", metadataObjects);
// 3. 設(shè)置界面顯示掃描結(jié)果
if (metadataObjects.count > 0){
AVMetadataMachineReadableCodeObject *obj = metadataObjects[0];
// 提示:如果需要對url或者名片等信息進(jìn)行掃描湃望,可以在此進(jìn)行擴(kuò)展换衬!
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证芭、生成二維碼的步驟: 導(dǎo)入CoreImage框架 通過濾鏡CIFilter生成二維碼
二維碼的內(nèi)容(傳統(tǒng)的條形碼只能放數(shù)字):純文本,名片,URL
// 1. 實例化二維碼濾鏡
CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
// 2. 恢復(fù)濾鏡的默認(rèn)屬性
[filter setDefaults];
// 3. 將字符串轉(zhuǎn)換成
NSData NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
// 4. 通過KVO設(shè)置濾鏡inputMessage數(shù)據(jù)
[filter setValue:data forKey:@"inputMessage"];
// 5. 獲得濾鏡輸出的圖像***
CIImage *outputImage = [filter outputImage];
// 6. 將CIImage轉(zhuǎn)換成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"];
//恢復(fù)濾鏡的默認(rèn)屬性
[filter setDefaults];
//將字符串轉(zhuǎn)換成NSData
NSData *data=[@"www.baidu.com" dataUsingEncoding:NSUTF8StringEncoding];
//通過KVO設(shè)置濾鏡inputmessage數(shù)據(jù)
[filter setValue:data forKey:@"inputMessage"];
//獲得濾鏡輸出的圖像
CIImage *outputImage=[filter outputImage];
//將CIImage轉(zhuǎn)換成UIImage,并放大顯示
_imgView.image=[self createNonInterpolatedUIImageFormCIImage:outputImage withSize:100.0];
//如果還想加上陰影废士,就在ImageView的Layer上使用下面代碼添加陰影
_imgView.layer.shadowOffset=CGSizeMake(0, 0.5);//設(shè)置陰影的偏移量
_imgView.layer.shadowRadius=1;//設(shè)置陰影的半徑
_imgView.layer.shadowColor=[UIColor blackColor].CGColor;//設(shè)置陰影的顏色為黑色
_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));
// 創(chuàng)建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];
}