之前都是第三方的二維碼,操作簡單pod集成,美滋滋。隨著公司項目越來越惡心到大,還是自己擼一個比較實在。
demo的主要功能掃描二維碼和生成二維碼。
掃描相關(guān)類
二維碼掃描需要獲取攝像頭并讀取照片信息,因此我們需要導(dǎo)入系統(tǒng)的AVFoundation框架,創(chuàng)建視頻會話。我們需要用到一下幾個類:
二維碼掃描功能的實現(xiàn)步驟是創(chuàng)建好會話對象,用來獲取從硬件設(shè)備輸入的數(shù)據(jù),并實時顯示在界面上。在掃描到相應(yīng)圖像數(shù)據(jù)的時候,通過AVCaptureVideoPreviewLayer類型進行返回
掃描二維碼
1.首先倒入框架
#import <AVFoundation/AVFoundation.h>
2.遵守協(xié)議
<AVCaptureMetadataOutputObjectsDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
3.主要用到的屬性設(shè)置
//捕獲設(shè)備,默認(rèn)后置攝像頭@property (strong, nonatomic) AVCaptureDevice * device;//輸入設(shè)備@property (strong, nonatomic) AVCaptureDeviceInput * input;//輸出設(shè)備,需要指定他的輸出類型及掃描范圍@property (strong, nonatomic) AVCaptureMetadataOutput * output;//AVFoundation框架捕獲類的中心樞紐,協(xié)調(diào)輸入輸出設(shè)備以獲得數(shù)據(jù)@property (strong, nonatomic) AVCaptureSession * session;//展示捕獲圖像的圖層,是CALayer的子類@property (strong, nonatomic) AVCaptureVideoPreviewLayer * preview;
4.拉起本地相冊二維碼
- (void)chooseButtonClick{if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {//關(guān)閉掃描[self stopScan];//1 彈出系統(tǒng)相冊UIImagePickerController *pickVC = [[UIImagePickerController alloc]init];//2 設(shè)置照片來源/**UIImagePickerControllerSourceTypePhotoLibrary,相冊UIImagePickerControllerSourceTypeCamera,相機UIImagePickerControllerSourceTypeSavedPhotosAlbum,照片庫*/pickVC.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;//3 設(shè)置代理pickVC.delegate = self;//4.轉(zhuǎn)場動畫self.modalTransitionStyle=UIModalTransitionStyleFlipHorizontal;[self presentViewController:pickVC animated:YES completion:nil];}else{[self showAlertViewWithTitle:@"打開失敗" withMessage:@"相冊打開失敗。設(shè)備不支持訪問相冊,請在設(shè)置->隱私->照片中進行設(shè)置!"];}}
生成二維碼
1.二維碼的生成
/*** 2.生成CIFilter(濾鏡)對象*/CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];/*** 3.恢復(fù)濾鏡默認(rèn)設(shè)置*/[filter setDefaults];/*** 4.設(shè)置數(shù)據(jù)(通過濾鏡對象的KVC)*///存放的信息NSString *info = @"hahahahhahahaha";//把信息轉(zhuǎn)化為NSDataNSData *infoData = [info dataUsingEncoding:NSUTF8StringEncoding];//濾鏡對象kvc存值[filter setValue:infoData forKeyPath:@"inputMessage"];/*** 5.生成二維碼*/CIImage *outImage = [filter outputImage];//imageView.image = [UIImage imageWithCIImage:outImage];//不處理圖片模糊,故而調(diào)用下面的信息self.codeImage.image = [outImage createNonInterpolatedWithSize:150];
2.保存到本地相冊
UIGraphicsBeginImageContext(self.view.bounds.size);[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];//獲取圖片UIImage * image = UIGraphicsGetImageFromCurrentImageContext();//關(guān)閉上下文UIGraphicsEndImageContext();completion(image);/*** 將圖片保存到本地相冊*/UIImageWriteToSavedPhotosAlbum(image, self , @selector(saveImage:didFinishSavingWithError:contextInfo:), nil);//保存圖片到照片庫
主要代碼貼出來,感興趣可以去gibHub地址:https://github.com/MrBMask 這里瞅瞅呦
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,如果有疑問大家可以留言交流,謝謝大家對VEVB武林網(wǎng)的支持。
新聞熱點
疑難解答
圖片精選