cocos2dx-lua在ios上實現生成及掃描二維碼
首先說明下,我是支援用iOS原生方法實現的。不過掃描二維碼原生方法不支援ios7.0之前的裝置,所以生成二維碼用的原生方法實現,而掃描二維碼用zBar sdk實現的(當然也可以用google官方的zXing sdk)。其中zBar中包含生成二維碼的方法,而且更多樣,我只是喜歡儘量用原生方法來實現。
這裡我把所有生成二維碼的程式碼和lua呼叫的掃描二維碼方法都放在了專案->frameworks->runtime-src->proj.ios_mac->ios->AppController.h和AppController.mm中
而zBar sdk及相關類放到了 專案->frameworks->runtime-src->proj.ios_mac->ios下。
-----1.原生生成二維碼
------------1.1AppController.h中新增程式碼:
- //生成二維碼
- +(CIImage *) creatQRcodeWithUrlstring:(NSString *)urlString;
- //改變圖片大小 (正方形圖片)
- + (UIImage *)changeImageSizeWithCIImage:(CIImage *)ciImage andSize:(CGFloat)size;
- //儲存(暫時沒用)
- +(BOOL)writeImage:(UIImage*)image toFileAtPath:(NSString*)aPath;
- //生成二維碼
- +(void)createQRCode:(NSDictionary *)info;
------------1.2AppController.mm中新增程式碼:
- /**
- * 根據字串生成二維碼 CIImage 物件
- *
- * @param urlString 需要生成二維碼的字串
- *
- * @return 生成的二維碼
- */
- + (CIImage *)creatQRcodeWithUrlstring:(NSString *)urlString{
- // 1.例項化二維碼濾鏡
- CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
- // 2.恢復濾鏡的預設屬性 (因為濾鏡有可能儲存上一次的屬性)
- [filter setDefaults];
- // 3.將字串轉換成NSdata
- NSData *data = [urlString dataUsingEncoding:NSUTF8StringEncoding];
- // 4.通過KVO設定濾鏡, 傳入data, 將來濾鏡就知道要通過傳入的資料生成二維碼
- [filter setValue:data forKey:@"inputMessage"];
- // 5.生成二維碼
- CIImage *outputImage = [filter outputImage];
- return outputImage;
- }
- /**
- * 改變圖片大小 (正方形圖片)
- *
- * @param ciImage 需要改變大小的CIImage 物件的圖片
- * @param size 圖片大小 (正方形圖片 只需要一個數)
- *
- * @return 生成的目標圖片
- */
- + (UIImage *)changeImageSizeWithCIImage:(CIImage *)ciImage andSize:(CGFloat)size{
- CGRect extent = CGRectIntegral(ciImage.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:ciImage 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];
- }
- + (BOOL)writeImage:(UIImage*)image toFileAtPath:(NSString*)aPath
- {
- if ((image == nil) || (aPath == nil) || ([aPath isEqualToString:@""]))
- return NO;
- @try
- {
- NSData *imageData = nil;
- NSString *ext = [aPath pathExtension];
- if ([ext isEqualToString:@"png"])
- {
- imageData = UIImagePNGRepresentation(image);
- }
- else
- {
- // the rest, we write to jpeg
- // 0. best, 1. lost. about compress.
- imageData = UIImageJPEGRepresentation(image, 0);
- }
- if ((imageData == nil) || ([imageData length] <= 0))
- return NO;
- [imageData writeToFile:aPath atomically:YES];
- return YES;
- }
- @catch (NSException *e)
- {
- NSLog(@"create thumbnail exception.");
- }
- return NO;
- }
- /*
- * 專案-TARGETS-fightGame-mobile-Build Phases-Link Binary With Libraries新增CoreImage.framework
- */
- +(void) createQRCode:(NSDictionary *)info
- {
- int _callBack = [[info objectForKey:@"listener"] intValue];
- NSString *qrCodeStr = [info objectForKey:@"qrCodeStr"];
- CIImage *ciImage = [self creatQRcodeWithUrlstring:qrCodeStr];
- UIImage *uiImage = [self changeImageSizeWithCIImage:ciImage andSize:180];
- NSData *imageData = UIImagePNGRepresentation(uiImage);
- std::string path = cocos2d::FileUtils::getInstance()->getWritablePath() + "qrCode.png";
- const char* pathC = path.c_str();
- NSString * pathN = [NSString stringWithUTF8String:pathC];
- bool isSuccess = [imageData writeToFile:pathN atomically:YES];
- cocos2d::LuaBridge::pushLuaFunctionById(_callBack);
- cocos2d::LuaValueDict dict;
- dict["isSuccess"] =cocos2d::LuaValue::booleanValue(isSuccess);
- cocos2d::LuaBridge::getStack()->pushLuaValueDict( dict );
- cocos2d::LuaBridge::getStack()->executeFunction(1);
- cocos2d::LuaBridge::releaseLuaFunctionById(_callBack);
- }
其中createQRcode方法為最終lua掉用oc的方法,將生成的圖片存到cocos2dx的writablePath下,並儲存為"qrCode.png"。最後在lua端取出用sprite顯示。
------------1.3lua呼叫createQRcode方法,並顯示
- local callBack = function (message)
- local filePath = cc.FileUtils:getInstance():getWritablePath()
- filePath = filePath.."qrCode.png"
- local rect = cc.rect(0, 0, 180, 180)
- local sprite = cc.Sprite:create()
- sprite:initWithFile(filePath, rect)
- sprite:setPosition(300, 300)
- self:addChild(sprite)
- end
- local info = {listener = callBack, qrCodeStr = "https://www.baidu.com/"}
- luaoc.callStaticMethod("AppController", "createQRCode", info)
------------1.4新增CoreImage.framework依賴框架(二維碼掃描需要用到)
專案->TARGETS->Build Phases->Link Binary With Libraries->左下角“+”號,search框中輸入CoreImage.framework,選擇匹配的選項即可。
-----2.zBar sdk實現二維碼掃描
------------2.1下載zBar sdk
地址在後面給出。
------------2.2將zBarSDK解壓並將解壓後的zBarSDK匯入到工程專案->frameworks->runtime-src->proj.ios_mac->ios下。
解壓後的zBarSDK目錄包含:Headers,libzbar.a,Resources。
如果匯入工程後沒有自動新增libzbar.a依賴框架,則需要手動新增該依賴框架(如1.4)。
------------2.3專案->frameworks->runtime-src->proj.ios_mac->ios->zBarSDK下新建ZCZBarViewController.h和ZCZBarViewController.mm兩個檔案,並匯入工程,程式碼如下。
------------2.4ZCZBarViewController.h程式碼:
- /*
- 版本說明 iOS研究院 305044955
- 1.8版本 剔除生成二維碼檔案,使用iOS7原生生成二維碼
- 1.7版本 修復了開啟相機點選,使用者如果點選拒絕,會導致崩潰的問題
- 1.6版本 增加了支援了區別條碼和二維碼,可以關閉掃描二維碼來增加條碼掃描速度
- 1.5版本 修正了iOS6下掃描會卡死,增加了iOS7下支援條形碼,修改了演算法,增加了效率
- 1.4版本 支援iOS8系統,修改了相應UI的適配問題
- 1.3版本 全新支援arm7s arm64 全新支援ARC
- 1.2版本 ZC封裝的ZBar二維碼SDK
- 1、更新類名從CustomViewController更改為ZCZBarViewController
- 2、刪除掉代理的相關程式碼
- 1.1版本 ZC封裝的ZBar二維碼SDK~
- 1、增加block回撥
- 2、取消代理
- 3、增加適配IOS7(ios7在AVFoundation中增加了掃描二維碼功能)
- 1.0版本 ZC封裝的ZBar二維碼SDK~1.0版本初始建立
- 二維碼編譯順序
- Zbar編譯
- 需要新增AVFoundation CoreMedia CoreVideo QuartzCore libiconv
- //示例程式碼
- 掃描程式碼
- BOOL代表是否關閉二維碼掃描,專門掃描條形碼
- ZCZBarViewController*vc=[[ZCZBarViewController alloc]initWithIsQRCode:NO Block:^(NSString *result, BOOL isFinish) {
- if (isFinish) {
- NSLog(@"最後的結果%@",result);
- }
- }];
- [self presentViewController:vc animated:YES completion:nil];
- 生成二維碼
- [ZCZBarViewController createImageWithImageView:imageView String:@"http://www.baidu.com"Scale:4];
- */
- #import <UIKit/UIKit.h>
- #import <AVFoundation/AVFoundation.h>
- #import "ZBarReaderController.h"
- #import <CoreImage/CoreImage.h>
- #define IOS7 [[[UIDevice currentDevice] systemVersion]floatValue]>=7
- @interface ZCZBarViewController : UIViewController<AVCaptureVideoDataOutputSampleBufferDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate,ZBarReaderDelegate,AVCaptureMetadataOutputObjectsDelegate>
- {
- int num;
- BOOL upOrdown;
- NSTimer * timer;
- UIImageView*_line;
- }
- @property (nonatomic,strong) AVCaptureVideoPreviewLayer *captureVideoPreviewLayer;
- @property (nonatomic, strong) AVCaptureSession *captureSession;
- @property (nonatomic, assign) BOOL isScanning;
- @property (nonatomic,copy)void(^ScanResult)(NSString*result,BOOL isSucceed);
- @property (nonatomic)BOOL isQRCode;
- //初始化函式
- -(id)initWithIsQRCode:(BOOL)isQRCode Block:(void(^)(NSString*,BOOL))a;
- //正規表示式對掃描結果篩選
- +(NSString*)zhengze:(NSString*)str;
- //建立二維碼
- +(void)createImageWithImageView:(UIImageView*)imageView String:(NSString*)str Scale:(CGFloat)scale;
- @end
------------2.4ZCZBarViewController.mm程式碼:
- #import "ZCZBarViewController.h"
- #import <AssetsLibrary/AssetsLibrary.h>
- @interface ZCZBarViewController ()
- @end
- #define WIDTH ( ([UIScreen mainScreen].bounds.size.width>[UIScreen mainScreen].bounds.size.height)?[UIScreen mainScreen].bounds.size.width:[UIScreen mainScreen].bounds.size.height )
- //[UIScreen mainScreen].bounds.size.width
- #define HEIGHT ( ([UIScreen mainScreen].bounds.size.width<[UIScreen mainScreen].bounds.size.height)?[UIScreen mainScreen].bounds.size.width:[UIScreen mainScreen].bounds.size.height )
- //[UIScreen mainScreen].bounds.size.height
- @implementation ZCZBarViewController
- - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
- {
- self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
- if (self) {
- // Custom initialization
- }
- return self;
- }
- -(id)initWithIsQRCode:(BOOL)isQRCode Block:(void(^)(NSString*,BOOL))a
- {
- if (self=[super init]) {
- self.ScanResult=a;
- self.isQRCode=isQRCode;
- }
- return self;
- }
- -(void)createView{
- //qrcode_scan_bg_Green_iphone5@2x.png qrcode_scan_bg_Green@2x.png
- UIImage*image= [UIImage imageNamed:@"qrcode_scan_bg_Green@2x.png"];
- float capWidth=image.size.width/2;
- float capHeight=image.size.height/2;
- image=[image stretchableImageWithLeftCapWidth:capWidth topCapHeight:capHeight];
- UIImageView* bgImageView=[[UIImageView alloc]initWithFrame:CGRectMake(0, 64, WIDTH, HEIGHT-64)];
- //bgImageView.contentMode=UIViewContentModeTop;
- bgImageView.clipsToBounds=YES;
- bgImageView.image=image;
- bgImageView.userInteractionEnabled=YES;
- [self.view addSubview:bgImageView];
- // UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(0, bgImageView.frame.size.height-140, WIDTH, 40)];
- // label.text = @"將取景框對準二維碼,即可自動掃描。";
- // label.textColor = [UIColor whiteColor];
- // label.textAlignment = NSTextAlignmentCenter;
- // label.lineBreakMode = NSLineBreakByWordWrapping;
- // label.numberOfLines = 2;
- // label.font=[UIFont systemFontOfSize:12];
- // label.backgroundColor = [UIColor clearColor];
- // [bgImageView addSubview:label];
- _line = [[UIImageView alloc] initWithFrame:CGRectMake((WIDTH-220)/2, 70, 220, 2)];
- _line.image = [UIImage imageNamed:@"qrcode_scan_light_green.png"];
- [bgImageView addSubview:_line];
- // //下方相簿
- // UIImageView*scanImageView=[[UIImageView alloc]initWithFrame:CGRectMake(0, HEIGHT-100, WIDTH, 100)];
- // scanImageView.image=[UIImage imageNamed:@"qrcode_scan_bar.png"];
- // scanImageView.userInteractionEnabled=YES;
- // [self.view addSubview:scanImageView];
- // NSArray*unSelectImageNames=@[@"qrcode_scan_btn_photo_nor.png",@"qrcode_scan_btn_flash_nor.png",@"qrcode_scan_btn_myqrcode_nor.png"];
- // NSArray*selectImageNames=@[@"qrcode_scan_btn_photo_down.png",@"qrcode_scan_btn_flash_down.png",@"qrcode_scan_btn_myqrcode_down.png"];
- //
- // for (int i=0; i<unSelectImageNames.count; i++) {
- // UIButton*button=[UIButton buttonWithType:UIButtonTypeCustom];
- // [button setImage:[UIImage imageNamed:unSelectImageNames[i]] forState:UIControlStateNormal];
- // [button setImage:[UIImage imageNamed:selectImageNames[i]] forState:UIControlStateHighlighted];
- // button.frame=CGRectMake(WIDTH/3*i, 0, WIDTH/3, 100);
- // [scanImageView addSubview:button];
- // if (i==0) {
- // [button addTarget:self action:@selector(pressPhotoLibraryButton:) forControlEvents:UIControlEventTouchUpInside];
- // }
- // if (i==1) {
- // [button addTarget:self action:@selector(flashLightClick) forControlEvents:UIControlEventTouchUpInside];
- // }
- // if (i==2) {
- // button.hidden=YES;
- // }
- //
- // }
- //假導航
- // UIImageView*navImageView=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 64)];
- // navImageView.image=[UIImage imageNamed:@"qrcode_scan_bar.png"];
- // navImageView.userInteractionEnabled=YES;
- // [self.view addSubview:navImageView];
- UILabel*titleLabel=[[UILabel alloc]initWithFrame:CGRectMake(WIDTH/2-32, 20, 64, 44)];
- titleLabel.textColor=[UIColor whiteColor];
- titleLabel.backgroundColor = [UIColor clearColor];
- titleLabel.text=@"掃一掃";
- [self.view addSubview:titleLabel];
- // [navImageView addSubview:titleLabel];
- UIButton*button = [UIButton buttonWithType:UIButtonTypeCustom];
- [button setImage:[UIImage imageNamed:@"qrcode_scan_titlebar_back_pressed@2x.png"] forState:UIControlStateHighlighted];
- [button setImage:[UIImage imageNamed:@"qrcode_scan_titlebar_back_nor.png"] forState:UIControlStateNormal];
- [button setFrame:CGRectMake(10,10, 48, 48)];
- [button addTarget:self action:@selector(pressCancelButton:) forControlEvents:UIControlEventTouchUpInside];
- [self.view addSubview:button];
- timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(animation1) userInfo:nil repeats:YES];
- }
- -(void)animation1
- {
- [UIView animateWithDuration:2 animations:^{
- _line.frame = CGRectMake((WIDTH-220)/2, 70+HEIGHT-310, 220, 2);
- }completion:^(BOOL finished) {
- [UIView animateWithDuration:2 animations:^{
- _line.frame = CGRectMake((WIDTH-220)/2, 70, 220, 2);
- }];
- }];
- }
- //開啟關閉閃光燈
- -(void)flashLightClick{
- AVCaptureDevice * device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
- if (device.torchMode==AVCaptureTorchModeOff) {
- //閃光燈開啟
- [device lockForConfiguration:nil];
- [device setTorchMode:AVCaptureTorchModeOn];
- }else {
- //閃光燈關閉
- [device setTorchMode:AVCaptureTorchModeOff];
- }
- }
- - (void)viewDidLoad
- {
- //相機介面的定製在self.view上載入即可
- BOOL Custom= [UIImagePickerController
- isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];//判斷攝像頭是否能用
- if (Custom) {
- [self initCapture];//啟動攝像頭
- }else{
- self.view.backgroundColor=[UIColor whiteColor];
- }
- [super viewDidLoad];
- [self createView];
- }
- #pragma mark 選擇相簿
- - (void)pressPhotoLibraryButton:(UIButton *)button
- { if (timer) {
- [timer invalidate];
- timer=nil;
- }
- _line.frame = CGRectMake((WIDTH-220)/2, 70, 220, 2);
- num = 0;
- upOrdown = NO;
- UIImagePickerController *picker = [[UIImagePickerController alloc] init];
- picker.allowsEditing = YES;
- picker.delegate = self;
- picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
- [self presentViewController:picker animated:YES completion:^{
- self.isScanning = NO;
- [self.captureSession stopRunning];
- }];
- }
- #pragma mark 點選取消
- - (void)pressCancelButton:(UIButton *)button
- {
- self.isScanning = NO;
- [self.captureSession stopRunning];
- self.ScanResult(nil,NO);
- if (timer) {
- [timer invalidate];
- timer=nil;
- }
- _line.frame = CGRectMake((WIDTH-220)/2, 70, 220, 2);
- num = 0;
- upOrdown = NO;
- [self dismissViewControllerAnimated:YES completion:nil];
- }
- #pragma mark 開啟相機
- - (void)initCapture
- {
- //ios6上也沒有“設定--隱私--相機” 那一項
- if (IOS7) {
- NSString *mediaType = AVMediaTypeVideo;
- AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
- if(authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied){
- NSString*str=[NSString stringWithFormat:@"請在系統設定-%@-相機中開啟允許使用相機", [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString*)kCFBundleNameKey]];
- UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:str delegate:nil cancelButtonTitle:@"確定" otherButtonTitles:nil, nil];
- [alert show];
- return;
- }
- }
- self.captureSession = [[AVCaptureSession alloc] init];
- AVCaptureDevice* inputDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
- AVCaptureDeviceInput *captureInput = [AVCaptureDeviceInput deviceInputWithDevice:inputDevice error:nil];
- [self.captureSession addInput:captureInput];
- AVCaptureVideoDataOutput *captureOutput = [[AVCaptureVideoDataOutput alloc] init];
- captureOutput.alwaysDiscardsLateVideoFrames = YES;
- if (IOS7) {
- AVCaptureMetadataOutput*_output=[[AVCaptureMetadataOutput alloc]init];
- [_output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
- [self.captureSession setSessionPreset:AVCaptureSessionPresetHigh];
- [self.captureSession addOutput:_output];
- //在這裡修改了,可以讓原生相容二維碼和條形碼,無需在使用Zbar
- if (_isQRCode) {
- _output.metadataObjectTypes =@[AVMetadataObjectTypeQRCode];
- }else{
- _output.metadataObjectTypes =@[AVMetadataObjectTypeEAN13Code,AVMetadataObjectTypeEAN8Code,AVMetadataObjectTypeCode128Code,AVMetadataObjectTypeQRCode];
- }
- if (!self.captureVideoPreviewLayer) {
- self.captureVideoPreviewLayer = [AVCaptureVideoPreviewLayer layerWithSession:self.captureSession];
- }
- // NSLog(@"prev %p %@", self.prevLayer, self.prevLayer);
- self.captureVideoPreviewLayer.frame = CGRectMake(0, 0, WIDTH, HEIGHT);//self.view.bounds;
- self.captureVideoPreviewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
- [self.view.layer addSublayer: self.captureVideoPreviewLayer];
- self.isScanning = YES;
- [self.captureSession startRunning];
- }else{
- dispatch_queue_t queue = dispatch_queue_create("myQueue", NULL);
- [captureOutput setSampleBufferDelegate:self queue:queue];
- NSString* key = (NSString *)kCVPixelBufferPixelFormatTypeKey;
- NSNumber* value = [NSNumber numberWithUnsignedInt:kCVPixelFormatType_32BGRA];
- NSDictionary *videoSettings = [NSDictionary dictionaryWithObject:value forKey:key];
- [captureOutput setVideoSettings:videoSettings];
- [self.captureSession addOutput:captureOutput];
- NSString* preset = 0;
- if (NSClassFromString(@"NSOrderedSet") && // Proxy for "is this iOS 5" ...
- [UIScreen mainScreen].scale > 1 &&
- [inputDevice
- supportsAVCaptureSessionPreset:AVCaptureSessionPresetiFrame960x540]) {
- // NSLog(@"960");
- preset = AVCaptureSessionPresetiFrame960x540;
- }
- if (!preset) {
- // NSLog(@"MED");
- preset = AVCaptureSessionPresetMedium;
- }
- self.captureSession.sessionPreset = preset;
- if (!self.captureVideoPreviewLayer) {
- self.captureVideoPreviewLayer = [AVCaptureVideoPreviewLayer layerWithSession:self.captureSession];
- }
- // NSLog(@"prev %p %@", self.prevLayer, self.prevLayer);
- self.captureVideoPreviewLayer.frame = CGRectMake(0, 0, WIDTH, HEIGHT);//self.view.bounds;
- self.captureVideoPreviewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
- [self.view.layer addSublayer: self.captureVideoPreviewLayer];
- self.isScanning = YES;
- [self.captureSession startRunning];
- }
- }
- - (UIImage *) imageFromSampleBuffer:(CMSampleBufferRef) sampleBuffer
- {
- CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);
- // Lock the base address of the pixel buffer
- CVPixelBufferLockBaseAddress(imageBuffer,0);
- // Get the number of bytes per row for the pixel buffer
- size_t bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer);
- // Get the pixel buffer width and height
- size_t width = CVPixelBufferGetWidth(imageBuffer);
- size_t height = CVPixelBufferGetHeight(imageBuffer);
- // Create a device-dependent RGB color space
- CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
- if (!colorSpace)
- {
- NSLog(@"CGColorSpaceCreateDeviceRGB failure");
- return nil;
- }
- // Get the base address of the pixel buffer
- void *baseAddress = CVPixelBufferGetBaseAddress(imageBuffer);
- // Get the data size for contiguous planes of the pixel buffer.
- size_t bufferSize = CVPixelBufferGetDataSize(imageBuffer);
- // Create a Quartz direct-access data provider that uses data we supply
- CGDataProviderRef provider = CGDataProviderCreateWithData(NULL, baseAddress, bufferSize,
- NULL);
- // Create a bitmap image from data supplied by our data provider
- CGImageRef cgImage =
- CGImageCreate(width,
- height,
- 8,
- 32,
- bytesPerRow,
- colorSpace,
- kCGImageAlphaNoneSkipFirst | kCGBitmapByteOrder32Little,
- provider,
- NULL,
- true,
- kCGRenderingIntentDefault);
- CGDataProviderRelease(provider);
- CGColorSpaceRelease(colorSpace);
- // Create and return an image object representing the specified Quartz image
- UIImage *image = [UIImage imageWithCGImage:cgImage];
- return image;
- }
- #pragma mark 對影象進行解碼
- - (void)decodeImage:(UIImage *)image
- {
- self.isScanning = NO;
- ZBarSymbol *symbol = nil;
- ZBarReaderController* read = [ZBarReaderController new];
- read.readerDelegate = self;
- CGImageRef cgImageRef = image.CGImage;
- for(symbol in [read scanImage:cgImageRef])break;
- if (symbol!=nil) {
- if (timer) {
- [timer invalidate];
- timer=nil;
- }
- _line.frame = CGRectMake((WIDTH-220)/2, 70, 220, 2);
- num = 0;
- upOrdown = NO;
- self.ScanResult(symbol.data,YES);
- [self.captureSession stopRunning];
- [self dismissViewControllerAnimated:YES completion:nil];
- }else{
- timer = [NSTimer scheduledTimerWithTimeInterval:.02 target:self selector:@selector(animation1) userInfo:nil repeats:YES];
- num = 0;
- upOrdown = NO;
- self.isScanning = YES;
- [self.captureSession startRunning];
- }
- }
- #pragma mark - AVCaptureVideoDataOutputSampleBufferDelegate
- - (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection
- {
- UIImage *image = [self imageFromSampleBuffer:sampleBuffer];
- [self decodeImage:image];
- }
- #pragma mark AVCaptureMetadataOutputObjectsDelegate//IOS7下觸發
- - (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
- {
- if (metadataObjects.count>0)
- {
- AVMetadataMachineReadableCodeObject * metadataObject = [metadataObjects objectAtIndex:0];
- self.ScanResult(metadataObject.stringValue,YES);
- }
- [self.captureSession stopRunning];
- _line.frame = CGRectMake((WIDTH-220)/2, 70, 220, 2);
- num = 0;
- upOrdown = NO;
- [self dismissViewControllerAnimated:YES completion:nil];
- }
- #pragma mark - UIImagePickerControllerDelegate
- - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
- {
- if (timer) {
- [timer invalidate];
- timer=nil;
- }
- _line.frame = CGRectMake((WIDTH-220)/2, 70, 220, 2);
- num = 0;
- upOrdown = NO;
- UIImage *image = [info objectForKey:@"UIImagePickerControllerEditedImage"];
- [self dismissViewControllerAnimated:YES completion:^{[self decodeImage:image];}];
- }
- - (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
- {
- if (timer) {
- [timer invalidate];
- timer=nil;
- }
- _line.frame = CGRectMake((WIDTH-220)/2, 70, 220, 2);
- num = 0;
- upOrdown = NO;
- timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(animation1) userInfo:nil repeats:YES];
- [self dismissViewControllerAnimated:YES completion:^{
- self.isScanning = YES;
- [self.captureSession startRunning];
- }];
- }
- #pragma mark - DecoderDelegate
- +(NSString*)zhengze:(NSString*)str
- {
- NSError *error;
- //http+:[^\\s]* 這是檢測網址的正規表示式
- NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"http+:[^\\s]*" options:0 error:&error];//篩選
- if (regex != nil) {
- NSTextCheckingResult *firstMatch = [regex firstMatchInString:str options:0 range:NSMakeRange(0, [str length])];
- if (firstMatch) {
- NSRange resultRange = [firstMatch rangeAtIndex:0];
- //從urlString中擷取資料
- NSString *result1 = [str substringWithRange:resultRange];
- NSLog(@"正則表達後的結果%@",result1);
- return result1;
- }
- }
- return nil;
- }
- +(void)createImageWithImageView:(UIImageView*)imageView String:(NSString*)str Scale:(CGFloat)scale{
- CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
- [filter setDefaults];
- NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
- [filter setValue:data forKey:@"inputMessage"];
- CIImage *outputImage = [filter outputImage];
- CIContext *context = [CIContext contextWithOptions:nil];
- CGImageRef cgImage = [context createCGImage:outputImage
- fromRect:[outputImage extent]];
- UIImage *image = [UIImage imageWithCGImage:cgImage
- scale:1.0
- orientation:UIImageOrientationUp];
- UIImage *resized = nil;
- CGFloat width = image.size.width*scale;
- CGFloat height = image.size.height*scale;
- UIGraphicsBeginImageContext(CGSizeMake(width, height));
- CGContextRef context1 = UIGraphicsGetCurrentContext();
- CGContextSetInterpolationQuality(context1, kCGInterpolationNone);
- [image drawInRect:CGRectMake(0, -50, width, height)];
- resized = UIGraphicsGetImageFromCurrentImageContext();
- UIGraphicsEndImageContext();
- imageView.image = resized;
- CGImageRelease(cgImage);
- }
- - (void)didReceiveMemoryWarning
- {
- [super didReceiveMemoryWarning];
- // Dispose of any resources that can be recreated.
- }
- /*
- #pragma mark - Navigation
- // In a storyboard-based application, you will often want to do a little preparation before navigation
- - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
- {
- // Get the new view controller using [segue destinationViewController].
- // Pass the selected object to the new view controller.
- }
- */
- ////支援旋轉
- //-(BOOL)shouldAutorotate{
- // return NO;
- //}
- ////支援的方向
- //- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
- // return UIInterfaceOrientationMaskPortrait;
- //}
- @end
------------2.5AppController.h中新增程式碼:
- //獲取當前正在顯示的ViewController
- + (UIViewController *)getCurrentVC;
- //獲取當前螢幕中present出來的viewcontroller。
- - (UIViewController *)getPresentedViewController;
- //掃描二維碼
- +(void)scanQRCode:(NSDictionary *)info;
------------2.5AppController.mm中新增程式碼:
- //獲取當前正在顯示的ViewController
- + (UIViewController *)getCurrentVC
- {
- UIViewController *result = nil;
- UIWindow * window = [[UIApplication sharedApplication] keyWindow];
- if (window.windowLevel != UIWindowLevelNormal)
- {
- NSArray *windows = [[UIApplication sharedApplication] windows];
- for(UIWindow * tmpWin in windows)
- {
- if (tmpWin.windowLevel == UIWindowLevelNormal)
- {
- window = tmpWin;
- break;
- }
- }
- }
- UIView *frontView = [[window subviews] objectAtIndex:0];
- id nextResponder = [frontView nextResponder];
- if ([nextResponder isKindOfClass:[UIViewController class]])
- result = nextResponder;
- else
- result = window.rootViewController;
- return result;
- }
- //獲取當前螢幕中present出來的viewcontroller。
- - (UIViewController *)getPresentedViewController
- {
- UIViewController *appRootVC = [UIApplication sharedApplication].keyWindow.rootViewController;
- UIViewController *topVC = appRootVC;
- if (topVC.presentedViewController) {
- topVC = topVC.presentedViewController;
- }
- return topVC;
- }
- +(void) scanQRCode:(NSDictionary *)info
- {
- int _callBack = [[info objectForKey:@"listener"] intValue];
- // SGScanningQRCodeVC *scanningQRCodeVC = [[SGScanningQRCodeVC alloc] init];
- // [scanningQRCodeVC setupScanningQRCode];
- UIViewController *nowViewController = [self getCurrentVC];
- ZCZBarViewController*vc=[[ZCZBarViewController alloc]initWithIsQRCode:NO Block:^(NSString *result, BOOL isFinish) {
- if (isFinish) {
- NSLog(@"最後的結果%@",result);
- UIViewController *nowViewController = [self getCurrentVC];
- dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.02 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
- [nowViewController dismissViewControllerAnimated:NO completion:nil];
- cocos2d::LuaBridge::pushLuaFunctionById(_callBack);
- cocos2d::LuaValueDict dict;
- dict["scanResult"] = cocos2d::LuaValue::stringValue([result UTF8String]);
- cocos2d::LuaBridge::getStack()->pushLuaValueDict(dict);
- cocos2d::LuaBridge::getStack()->executeFunction(1);
- cocos2d::LuaBridge::releaseLuaFunctionById(_callBack);
- });
- }
- }];
- [nowViewController presentViewController:vc animated:YES completion:nil];
- }
其中scanQRCode方法為最終lua掉用oc的方法,在掃描識別出二維碼資訊之後會將資訊傳回給lua端。
------------2.6lua掉用oc掃描二維碼程式碼:
- local callBack = function (message)
- print("message scanResult : ", message.scanResult)
- Utils.showTip(message.scanResult)
- end
- local info = {listener = callBack}
- luaoc.callStaticMethod("AppController", "scanQRCode", info)
------------2.7新增依賴框架
如上1.4,掃描二維碼需要新增框架AVFoundation, CoreMedie, CoreVideo, QuartzCore, libiconv
-----3.掃描介面橫豎屏說明
如果遊戲介面是橫屏的,而二維碼掃描介面要求是豎屏的,則需要做些操作。
------------3.1增加豎屏支援
專案->TARGETS->General->Deployment Info->Device Orientation->勾選Portrait,Landscape Left, Landscape Right。
------------3.2讓遊戲介面只支援橫屏
專案->frameworks->runtime-src->proj.ios_mac->ios->RootViewController.mm中supportedInterfaceOrientations方法修改為:
- // For ios6, use supportedInterfaceOrientations & shouldAutorotate instead
- - (NSUInteger) supportedInterfaceOrientations{
- return UIInterfaceOrientationMaskLandscapeLeft | UIInterfaceOrientationMaskLandscapeRight;
- //#ifdef __IPHONE_6_0
- // return UIInterfaceOrientationMaskAllButUpsideDown;
- //#endif
- }
------------3.3掃描二維碼介面只支援豎屏
專案->frameworks->runtime-src->proj.ios_mac->ios->ZCZBarViewController.mm中增加程式碼:
- ////支援旋轉
- //-(BOOL)shouldAutorotate{
- // return NO;
- //}
- ////支援的方向
- //- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
- // return UIInterfaceOrientationMaskPortrait;
- //}
------------3.4修改view介面width和height重新適配
專案->frameworks->runtime-src->proj.ios_mac->ios->ZCZBarViewController.mm中將
#define WIDTH和#define HEIGHT兩個巨集的值顛倒下。
-----4.關於專案->frameworks->runtime-src->proj.ios_mac->ios->ZCZBarViewController.mm中#define WIDTH和#define HEIGHT兩個巨集
本來因該是
#define WIDTH [UIScreen mainScreen].bounds.size.width
#define HEIGHT [UIScreen mainScreen].bounds.size.height
但在iphone4s(ios6.1.3)上取出的width和height為320, 480,而在iPhone6 Plus(ios10.2)上width和height為568, 320。
一個寬小於高,一個寬大於高,使得4s橫屏的時候,6Plus豎屏是對的,而在6Plus上橫屏就是亂的。
所以後來將兩個巨集修改為(注意:兩邊一定要帶括號,防止編譯時巨集展開後由於操作符優先順序導致的運算錯誤)
#define WIDTH ( ([UIScreen mainScreen].bounds.size.width>[UIScreen mainScreen].bounds.size.height)?[UIScreen mainScreen].bounds.size.width:[UIScreen mainScreen].bounds.size.height )
#define HEIGHT ( ([UIScreen mainScreen].bounds.size.width<[UIScreen mainScreen].bounds.size.height)?[UIScreen mainScreen].bounds.size.width:[UIScreen mainScreen].bounds.size.height )
從而將寬固定取獲得的二者較大值,高為二者較小值。若是豎屏,則反過來。
-----5.遇到的一些問題
------------5.1對於ZCZBarViewController.mm中的initCpture方法中有句
AVAuthorizationStatus authStatus = [AVCaptureDeviceauthorizationStatusForMediaType:mediaType];
注意:此方法只對ios7以上的系統有用,如果是在ios6的系統的話就直接崩潰了,況且ios6上也沒有“設定--隱私--相機”那一項。
所以加了if(IOS7)的判斷。
------------5.2若碰到錯誤Cannot synthesize weak property in file using manual reference counting
專案->TARGETS->Build Settings->Apple LLVM 8.0-Language-Objective C->Weak References in Manual Retian Release改為YES
------------5.3編譯報錯XXXX.o
若編譯執行報錯,XXXX.o什麼什麼的問題,則可能是有依賴框架沒有匯入。
-----6.參考連結
//原生生成二維碼
http://blog.csdn.net/zhuming3834/article/details/50832953
//原生二維碼掃描
http://www.cocoachina.com/ios/20161009/17696.html
//zBar下載地址
http://download.csdn.net/download/kid_devil/7552613
//zBarDemo下載地址
http://download.csdn.net/detail/shan1991fei/9474417
//二維碼掃描之zXing與zBar的優劣
相關文章
- iOS 掃描二維碼/條形碼2018-12-10iOS
- zxing第三方框架實現二維碼掃描以及生成2018-12-03框架
- Android----二維碼掃描、生成、相簿識別(16號)2018-08-12Android
- XQRCode 一個非常方便實用的二維碼掃描、解析、生成庫2018-05-07
- 基於ZXingAndroid實現生成二維碼圖片和相機掃描二維碼圖片即時解碼的功能2018-03-29Android
- 掃描二維碼登入思路2019-05-20
- 基於ZXing Android實現生成二維碼圖片和相機掃描二維碼圖片即時解碼的功能2018-03-29Android
- Android 基於zxing的二維碼掃描功能的簡單實現及優化2018-07-29Android優化
- ios--二維碼生成2020-04-05iOS
- java實現二維碼生成2018-06-06Java
- iOS 生成二維碼/條形碼2018-12-17iOS
- 二維碼線上生成2024-11-05
- iOS 二維碼生成以及識別2019-02-21iOS
- 簡單易用的二維碼掃描工具:QR Capture for Mac2021-01-08APTMac
- 全棧工程師之路-React Native之掃描二維碼2018-03-30全棧工程師React Native
- QRCode 生成二維碼,覆蓋在固定海報上2019-01-15
- 使用HTML5實現掃描PC二維碼且觸發WAP端上傳資源功能2020-09-22HTML
- PHP掃描圖片轉點陣 二維碼轉點陣2020-08-09PHP
- Swift4如何掃描二維碼瞭解一下2018-04-20Swift
- 一對一直播系統開發如何在頁面內實現掃描二維碼功能2020-08-21
- spring boot高效能實現二維碼掃碼登入(上)——單伺服器版2018-03-25Spring Boot伺服器
- apk 生成二維碼,手機掃碼即裝的便捷工具2020-07-03APK
- 智慧公安二維碼報警系統研發解決方案-隨時隨地掃描二維碼2020-12-23
- 線上生成二維碼的API介面2018-05-21API
- Go 實現埠掃描器2023-04-13Go
- 二維碼生成2018-09-05
- 掃二維碼連wifi2020-04-06WiFi
- iOS 11 相機二維碼掃描存在漏洞 會導致使用者訪問惡意網站2018-03-27iOS網站
- 微信小程式掃描普通二維碼開啟小程式的方法2021-12-03微信小程式
- sonar(二)掃描配置2024-05-09
- 多檔案二維碼生成器線上報名功能,wps線上生成二維碼線上預覽線上分享2024-04-12
- 二維碼管理平臺 生成二維碼2019-05-11
- GO語言 實現埠掃描2020-12-04Go
- spring boot高效能實現二維碼掃碼登入(中)——Redis版2018-03-25Spring BootRedis
- 趣味二維碼生成2022-05-11
- 二維碼生成-Python2020-11-08Python
- PC客戶端Winform掃描微信二維碼登入網站Navite2024-07-19客戶端ORM網站Vite
- 條碼列印軟體是否可以製作只能掃描一次的二維碼?2023-04-03
- Flutter - 生成二維碼與識別二維碼2018-08-12Flutter