首先说明下,我是支持用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中添加代码:
[cpp] view plain copy //生成二维码 +(CIImage*)creatQRcodeWithUrlstring:(Nsstring*)urlString; //改变图片大小(正方形图片) +(UIImage*)changeImageSizeWithCIImage:(CIImage*)ciImageandSize:(CGfloat)size; //保存(暂时没用) +(BOol)writeImage:(UIImage*)imagetofileAtPath:(Nsstring*)aPath; +(voID)createQRCode:(NSDictionary*)info;------------1.2AppController.mm中添加代码:
其中createQRcode方法为最终lua掉用oc的方法,将生成的图片存到cocos2dx的writablePath下,并保存为"qrCode.png"。最后在lua端取出用sprite显示。
------------1.3lua调用createQRcode方法,并显示
copy localcallBack=function(message) localfilePath=cc.fileUtils:getInstance():getWritablePath() filePath=filePath.."qrCode.png" localrect=cc.rect(0,180,180) localsprite=cc.Sprite:create() sprite:initWithfile(filePath,rect) sprite:setposition(300,300) self:addChild(sprite) end localinfo={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导入到工程解压后的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代码:
------------2.4ZCZbarVIEwController.mm代码:
copy #import"ZCZbarVIEwController.h" #import<AssetsLibrary/AssetsLibrary.h> @interfaceZCZbarVIEwController() @end #defineWIDTH(([UIScreenmainScreen].bounds.size.wIDth>[UIScreenmainScreen].bounds.size.height)?[UIScreenmainScreen].bounds.size.wIDth:[UIScreenmainScreen].bounds.size.height) //[UIScreenmainScreen].bounds.size.wIDth #defineHEIGHT(([UIScreenmainScreen].bounds.size.wIDth<[UIScreenmainScreen].bounds.size.height)?[UIScreenmainScreen].bounds.size.wIDth:[UIScreenmainScreen].bounds.size.height) //[UIScreenmainScreen].bounds.size.height @implementationZCZbarVIEwController -(ID)initWithNibname:(Nsstring*)nibnameOrNilbundle:(NSBundle*)nibBundleOrNil self=[superinitWithNibname:nibnameOrNilbundle:nibBundleOrNil]; if(self){ //Custominitialization returnself; BOol))a if(self=[superinit]){ self.ScanResult=a; self.isQRCode=isQRCode; -(voID)createVIEw{ //qrcode_scan_bg_Green_iphone5@2x.pngqrcode_scan_bg_Green@2x.png UIImage*image=[UIImageimagenamed:@"qrcode_scan_bg_Green@2x.png"]; floatcapWIDth=image.size.wIDth/2; floatcapHeight=image.size.height/2; image=[imagestretchableImageWithleftCapWIDth:capWIDthtopCapHeight:capHeight]; UIImageVIEw*bgImageVIEw=[[UIImageVIEwalloc]initWithFrame:CGRectMake(0,64,WIDTH,HEIGHT-64)]; //bgImageVIEw.contentMode=UIVIEwContentModetop; bgImageVIEw.clipsToBounds=YES; bgImageVIEw.image=image; bgImageVIEw.userInteractionEnabled=YES; [self.vIEwaddSubvIEw:bgImageVIEw]; //UILabel*label=[[UILabelalloc]initWithFrame:CGRectMake(0,bgImageVIEw.frame.size.height-140,40)]; //label.text=@"将取景框对准二维码,即可自动扫描。"; //label.textcolor=[UIcolorwhitecolor]; //label.textAlignment=NSTextAlignmentCenter; //label.lineBreakMode=NSlineBreakByWorDWrapPing; //label.numberOflines=2; //label.Font=[UIFontsystemFontOfSize:12]; //label.backgroundcolor=[UIcolorclearcolor]; //[bgImageVIEwaddSubvIEw:label]; _line=[[UIImageVIEwalloc]initWithFrame:CGRectMake((WIDTH-220)/2,70,220,2)]; _line.image=[UIImageimagenamed:@"qrcode_scan_light_green.png"]; [bgImageVIEwaddSubvIEw:_line]; ////下方相册 //UIImageVIEw*scanImageVIEw=[[UIImageVIEwalloc]initWithFrame:CGRectMake(0,HEIGHT-100,100)]; //scanImageVIEw.image=[UIImageimagenamed:@"qrcode_scan_bar.png"]; //scanImageVIEw.userInteractionEnabled=YES; //[self.vIEwaddSubvIEw: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(inti=0;i<unSelectimagenames.count;i++){ //UIbutton*button=[UIbuttonbuttonWithType:UIbuttonTypeCustom]; //[buttonsetimage:[UIImageimagenamed:unSelectimagenames[i]]forState:UIControlStatenormal]; //[buttonsetimage:[UIImageimagenamed:selectimagenames[i]]forState:UIControlStateHighlighted]; //button.frame=CGRectMake(WIDTH/3*i,WIDTH/3,100); //[scanImageVIEwaddSubvIEw:button]; //if(i==0){ //[buttonaddTarget:selfaction:@selector(pressphotolibrarybutton:)forControlEvents:UIControlEventtouchUpInsIDe]; //} //if(i==1){ //[buttonaddTarget:selfaction:@selector(flashlightClick)forControlEvents:UIControlEventtouchUpInsIDe]; //} //if(i==2){ //button.hIDden=YES; //假导航 //UIImageVIEw*navImageVIEw=[[UIImageVIEwalloc]initWithFrame:CGRectMake(0,64)]; //navImageVIEw.image=[UIImageimagenamed:@"qrcode_scan_bar.png"]; //navImageVIEw.userInteractionEnabled=YES; //[self.vIEwaddSubvIEw:navImageVIEw]; UILabel*@R_301_5979@Label=[[UILabelalloc]initWithFrame:CGRectMake(WIDTH/2-32,20,44)]; @R_301_5979@Label.textcolor=[UIcolorwhitecolor]; @R_301_5979@Label.backgroundcolor=[UIcolorclearcolor]; @R_301_5979@Label.text=@"扫一扫"; [self.vIEwaddSubvIEw:@R_301_5979@Label]; //[navImageVIEwaddSubvIEw:@R_301_5979@Label]; UIbutton*button=[UIbuttonbuttonWithType:UIbuttonTypeCustom]; [buttonsetimage:[UIImageimagenamed:@"qrcode_scan_@R_301_5979@bar_back_pressed@2x.png"]forState:UIControlStateHighlighted]; [buttonsetimage:[UIImageimagenamed:@"qrcode_scan_@R_301_5979@bar_back_nor.png"]forState:UIControlStatenormal]; [buttonsetFrame:CGRectMake(10,10,48,48)]; [buttonaddTarget:selfaction:@selector(pressCancelbutton:)forControlEvents:UIControlEventtouchUpInsIDe]; [self.vIEwaddSubvIEw:button]; timer=[NSTimerscheduledTimerWithTimeInterval:2target:selfselector:@selector(animation1)userInfo:nilrepeats:YES]; -(voID)animation1 [UIVIEwanimateWithDuration:2animations:^{ _line.frame=CGRectMake((WIDTH-220)/2,70+HEIGHT-310,2); }completion:^(BOolfinished){ _line.frame=CGRectMake((WIDTH-220)/2,2); }]; //开启关闭闪光灯 voID)flashlightClick{ AVCaptureDevice*device=[AVCaptureDevicedefaultDeviceWithMediaType:AVMediaTypeVIDeo]; if(device.torchMode==AVCapturetorchModeOff){ //闪光灯开启 [devicelockForConfiguration:nil]; [devicesetTorchMode:AVCapturetorchModeOn]; }else{ //闪光灯关闭 [devicesetTorchMode:AVCapturetorchModeOff]; voID)vIEwDIDLoad //相机界面的定制在self.vIEw上加载即可 BOolCustom=[UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];//判断摄像头是否能用 if(Custom){ [selfinitCapture];//启动摄像头 self.vIEw.backgroundcolor=[UIcolorwhitecolor]; [supervIEwDIDLoad]; [selfcreateVIEw]; #pragmamark选择相册 voID)pressphotolibrarybutton:(UIbutton*)button {if(timer){ [timerinvalIDate]; timer=nil; num=0; upOrdown=NO; UIImagePickerController*picker=[[UIImagePickerControlleralloc]init]; picker.allowsEditing=YES; picker.delegate=self; picker.sourceType=UIImagePickerControllerSourceTypePhotolibrary; [selfpresentVIEwController:pickeranimated:YEScompletion:^{ self.isScanning=NO; [self.captureSessionstopRunning]; }]; #pragmamark点击取消 voID)pressCancelbutton:(UIbutton*)button self.isScanning=NO; [self.captureSessionstopRunning]; self.ScanResult(nil,NO); if(timer){ [timerinvalIDate]; timer=nil; num=0; upOrdown=NO; [selfdismissVIEwControllerAnimated:YEScompletion:nil]; #pragmamark开启相机 voID)initCapture //ios6上也没有“设置--隐私--相机”那一项 if(IOS7){ Nsstring*mediaType=AVMediaTypeVIDeo; AVAuthorizationStatusauthStatus=[AVCaptureDeviceauthorizationStatusForMediaType:mediaType]; if(authStatus==AVAuthorizationStatusRestricted||authStatus==AVAuthorizationStatusDenIEd){ Nsstring*str=[NsstringstringWithFormat:@"请在系统设置-%@-相机中打开允许使用相机",[[[NSBundlemainBundle]infoDictionary]objectForKey:(Nsstring*)kcfBundlenameKey]]; UIAlertVIEw*alert=[[UIAlertVIEwalloc]initWith@R_301_5979@:@"提示"message:strdelegate:nilcancelbutton@R_301_5979@:@"确定"otherbutton@R_301_5979@s:nil,nil]; [alertshow]; return; self.captureSession=[[AVCaptureSessionalloc]init]; AVCaptureDevice*inputDevice=[AVCaptureDevicedefaultDeviceWithMediaType:AVMediaTypeVIDeo]; AVCaptureDeviceinput*captureinput=[AVCaptureDeviceinputdeviceinputWithDevice:inputDeviceerror:nil]; [self.captureSessionaddinput:captureinput]; AVCaptureVIDeoDataOutput*captureOutput=[[AVCaptureVIDeoDataOutputalloc]init]; captureOutput.alwaysdiscardsLateVIDeoFrames=YES; if(IOS7){ AVCaptureMetadataOutput*_output=[[AVCaptureMetadataOutputalloc]init]; [_outputsetMetadataObjectsDelegate:selfqueue:dispatch_get_main_queue()]; [self.captureSessionsetSessionPreset:AVCaptureSessionPresetHigh]; [self.captureSessionaddOutput:_output]; //在这里修改了,可以让原生兼容二维码和条形码,无需在使用Zbar if(_isQRCode){ _output.MetadataObjectTypes=@[AVMetadataObjectTypeQRCode]; }else{ _output.MetadataObjectTypes=@[AVMetadataObjectTypeEAN13Code,AVMetadataObjectTypeEAN8Code,AVMetadataObjectTypeCode128Code,AVMetadataObjectTypeQRCode]; if(!self.captureVIDeoPrevIEwLayer){ self.captureVIDeoPrevIEwLayer=[AVCaptureVIDeoPrevIEwLayerlayerWithSession:self.captureSession]; //NSLog(@"prev%p%@",self.prevLayer,self.prevLayer); self.captureVIDeoPrevIEwLayer.frame=CGRectMake(0,HEIGHT);//self.vIEw.bounds; self.captureVIDeoPrevIEwLayer.vIDeoGravity=AVLayerVIDeoGravityResizeAspectFill; [self.vIEw.layeraddSublayer:self.captureVIDeoPrevIEwLayer]; self.isScanning=YES; [self.captureSessionstartRunning]; dispatch_queue_tqueue=dispatch_queue_create("myQueue",NulL); [captureOutputsetSampleBufferDelegate:selfqueue:queue]; Nsstring*key=(Nsstring*)kCVPixelBufferPixelFormatTypeKey; NSNumber*value=[NSNumbernumberWithUnsignedInt:kCVPixelFormatType_32BGRA]; NSDictionary*vIDeoSettings=[NSDictionarydictionaryWithObject:valueforKey:key]; [captureOutputsetVIDeoSettings:vIDeoSettings]; [self.captureSessionaddOutput:captureOutput]; Nsstring*preset=0; if(NSClassFromString(@"NSOrderedSet")&&//Proxyfor"isthisiOS5"... [UIScreenmainScreen].scale>1&& [inputDevice supportsAVCaptureSessionPreset:AVCaptureSessionPresetiframe960x540]){ //NSLog(@"960"); preset=AVCaptureSessionPresetiframe960x540; if(!preset){ //NSLog(@"MED"); preset=AVCaptureSessionPresetMedium; self.captureSession.sessionPreset=preset; if(!self.captureVIDeoPrevIEwLayer){ self.captureVIDeoPrevIEwLayer=[AVCaptureVIDeoPrevIEwLayerlayerWithSession:self.captureSession]; self.captureVIDeoPrevIEwLayer.frame=CGRectMake(0,0); background-color: inherit;">//self.vIEw.bounds; self.captureVIDeoPrevIEwLayer.vIDeoGravity=AVLayerVIDeoGravityResizeAspectFill; [self.vIEw.layeraddSublayer:self.captureVIDeoPrevIEwLayer]; self.isScanning=YES; [self.captureSessionstartRunning]; -(UIImage*)imageFromSampleBuffer:(CMSampleBufferRef)sampleBuffer CVImageBufferRefimageBuffer=CMSampleBufferGetimageBuffer(sampleBuffer); //Lockthebaseaddressofthepixelbuffer CVPixelBufferLockBaseAddress(imageBuffer,0); background-color: inherit;">//Getthenumberofbytesperrowforthepixelbuffer size_tbytesPerRow=CVPixelBufferGetBytesPerRow(imageBuffer); //GetthepixelbufferwIDthandheight size_twIDth=CVPixelBufferGetWIDth(imageBuffer); size_theight=CVPixelBufferGetHeight(imageBuffer); //Createadevice-dependentRGBcolorspace CGcolorSpaceRefcolorSpace=CGcolorSpaceCreateDeviceRGB(); if(!colorSpace) NSLog(@"CGcolorSpaceCreateDeviceRGBfailure"); returnnil; //Getthebaseaddressofthepixelbuffer voID*baseAddress=CVPixelBufferGetBaseAddress(imageBuffer); //Getthedatasizeforcontiguousplanesofthepixelbuffer. size_tbufferSize=CVPixelBufferGetDataSize(imageBuffer); //CreateaQuartzdirect-accessdataprovIDerthatusesdatawesupply CGDataProvIDerRefprovIDer=CGDataProvIDerCreateWithData(NulL,baseAddress,bufferSize, NulL); //CreateabitmAPImagefromdatasupplIEdbyourdataprovIDer CGImageRefcgImage= CGImageCreate(wIDth,248); line-height: 18px; padding: 0px 3px 0px 10px !important; List-style-position: outsIDe !important;">height, 8,248); line-height: 18px; padding: 0px 3px 0px 10px !important; List-style-position: outsIDe !important;">32,108); border-image: initial; List-style-image: initial; color: inherit; line-height: 18px; padding: 0px 3px 0px 10px !important; List-style-position: outsIDe !important;">bytesPerRow,248); line-height: 18px; padding: 0px 3px 0px 10px !important; List-style-position: outsIDe !important;">colorSpace,108); border-image: initial; List-style-image: initial; color: inherit; line-height: 18px; padding: 0px 3px 0px 10px !important; List-style-position: outsIDe !important;">kCGImageAlphaNoneskipFirst|kCGBitmapByteOrder32little,248); line-height: 18px; padding: 0px 3px 0px 10px !important; List-style-position: outsIDe !important;">provIDer,108); border-image: initial; List-style-image: initial; color: inherit; line-height: 18px; padding: 0px 3px 0px 10px !important; List-style-position: outsIDe !important;">NulL,153); background-color: inherit; Font-weight: bold;">true, kCGRenderingIntentDefault); CGDataProvIDerRelease(provIDer); CGcolorSpaceRelease(colorSpace); //CreateandreturnanimageobjectrepresentingthespecifIEdQuartzimage UIImage*image=[UIImageimageWithCGImage:cgImage]; returnimage; #pragmamark对图像进行解码 voID)decodeImage:(UIImage*)image ZbarSymbol*symbol=nil; ZbarReaderController*read=[ZbarReaderControllernew]; read.readerDelegate=self; CGImageRefcgImageRef=image.CGImage; for(symbolin[readscanImage:cgImageRef])break; if(symbol!=nil){ self.ScanResult(symbol.data,YES); [selfdismissVIEwControllerAnimated:YEScompletion:nil]; timer=[NSTimerscheduledTimerWithTimeInterval:.02target:selfselector:@selector(animation1)userInfo:nilrepeats:YES]; #pragmamark-AVCaptureVIDeoDataOutputSampleBufferDelegate voID)captureOutput:(AVCaptureOutput*)captureOutputdIDOutputSampleBuffer:(CMSampleBufferRef)sampleBufferfromConnection:(AVCaptureConnection*)connection UIImage*image=[selfimageFromSampleBuffer:sampleBuffer]; [selfdecodeImage:image]; #pragmamarkAVCaptureMetadataOutputObjectsDelegate//IOS7下触发 voID)captureOutput:(AVCaptureOutput*)captureOutputdIDOutputMetadataObjects:(NSArray*)MetadataObjectsfromConnection:(AVCaptureConnection*)connection if(MetadataObjects.count>0) AVMetadataMachineReadableCodeObject*MetadataObject=[MetadataObjectsobjectAtIndex:0]; self.ScanResult(MetadataObject.stringValue,108); border-image: initial; List-style-image: initial; color: inherit; line-height: 18px; padding: 0px 3px 0px 10px !important; List-style-position: outsIDe !important;">#pragmamark-UIImagePickerControllerDelegate voID)imagePickerController:(UIImagePickerController*)pickerdIDFinishPickingMediawithInfo:(NSDictionary*)info UIImage*image=[infoobjectForKey:@"UIImagePickerControllerEditedImage"]; [selfdismissVIEwControllerAnimated:YEScompletion:^{[selfdecodeImage:image];}]; voID)imagePickerControllerDIDCancel:(UIImagePickerController*)picker [selfdismissVIEwControllerAnimated:YEScompletion:^{ #pragmamark-DecoderDelegate +(Nsstring*)zhengze:(Nsstring*)str NSError*error; //http+:[^\\s]*这是检测网址的正则表达式 NSRegularExpression*regex=[NSRegularExpressionregularExpressionWithPattern:@"http+:[^\s]*"options:0error:&error];//筛选 if(regex!=nil){ NSTextCheckingResult*firstMatch=[regexfirstMatchInString:stroptions:0range:NSMakeRange(0,[strlength])]; if(firstMatch){ NSRangeresultRange=[firstMatchrangeAtIndex:0]; //从urlString中截取数据 Nsstring*result1=[strsubstringWithRange:resultRange]; NSLog(@"正则表达后的结果%@",result1); returnresult1; returnnil; voID)createImageWithImageVIEw:(UIImageVIEw*)imageVIEwString:(Nsstring*)strScale:(CGfloat)scale{ [filtersetDefaults]; NSData*data=[strdataUsingEnCoding:NSUTF8StringEnCoding]; CIContext*context=[CIContextcontextWithOptions:nil]; CGImageRefcgImage=[contextcreateCGImage:outputimage fromrect:[outputimageextent]]; UIImage*image=[UIImageimageWithCGImage:cgImage scale:1.0 orIEntation:UIImageOrIEntationUp]; UIImage*resized=nil; CGfloatwIDth=image.size.wIDth*scale; CGfloatheight=image.size.height*scale; UIGraphicsBeginImageContext(CGSizeMake(wIDth,height)); CGContextRefcontext1=UIGraphicsGetCurrentContext(); CGContextSetInterpolationQuality(context1,kCGInterpolationNone); [imagedrawInRect:CGRectMake(0,-50,height)]; resized=UIGraphicsGetimageFromCurrentimageContext(); UIGraphicsEndImageContext(); imageVIEw.image=resized; CGImageRelease(cgImage); voID)dIDReceiveMemoryWarning [superdIDReceiveMemoryWarning]; //dispoSEOfanyresourcesthatcanberecreated. /* #pragmamark-Navigation //Inastoryboard-basedapplication,youwilloftenwanttodoalittlepreparationbeforenavigation -(voID)prepareForSegue:(UIStoryboardSegue*)seguesender:(ID)sender { //GetthenewvIEwcontrollerusing[seguedestinationVIEwController]. //PasstheselectedobjecttothenewvIEwcontroller. } ////支持旋转 //-(BOol)shouldautorotate{ //returnNO; ////支持的方向 //-(UIInterfaceOrIEntationMask)supportedInterfaceOrIEntations{ //returnUIInterfaceOrIEntationMaskPortrait; @end
------------2.5AppController.h中添加代码:
copy //获取当前正在显示的VIEwController +(UIVIEwController*)getCurrentVC; //获取当前屏幕中present出来的vIEwcontroller。 -(UIVIEwController*)getPresentedVIEwController; //扫描二维码 voID)scanQRCode:(NSDictionary*)info;
------------2.5AppController.mm中添加代码:
copy +(UIVIEwController*)getCurrentVC UIVIEwController*result=nil; UIWindow*window=[[UIApplicationsharedApplication]keyWindow]; if(window.windowLevel!=UIWindowLevelnormal) NSArray*windows=[[UIApplicationsharedApplication]windows]; for(UIWindow*tmpWininwindows) if(tmpWin.windowLevel==UIWindowLevelnormal) window=tmpWin; break; UIVIEw*frontVIEw=[[windowsubvIEws]objectAtIndex:0]; IDnextResponder=[frontVIEwnextResponder]; if([nextResponderisKindOfClass:[UIVIEwControllerclass]]) result=nextResponder; result=window.rootVIEwController; returnresult; //获取当前屏幕中present出来的vIEwcontroller。 -(UIVIEwController*)getPresentedVIEwController UIVIEwController*appRootVC=[UIApplicationsharedApplication].keyWindow.rootVIEwController; UIVIEwController*topVC=appRootVC; if(topVC.presentedVIEwController){ topVC=topVC.presentedVIEwController; returntopVC; voID)scanQRCode:(NSDictionary*)info //SGScanningQRCodeVC*scanningQRCodeVC=[[SGScanningQRCodeVCalloc]init]; //[scanningQRCodeVCsetupScanningQRCode]; UIVIEwController*NowVIEwController=[selfgetCurrentVC]; ZCZbarVIEwController*vc=[[ZCZbarVIEwControlleralloc]initWithIsQRCode:NOBlock:^(Nsstring*result,BOolisFinish){ if(isFinish){ NSLog(@"最后的结果%@",result); UIVIEwController*NowVIEwController=[selfgetCurrentVC]; dispatch_after(dispatch_time(disPATCH_TIME_Now,(int64_t)(0.02*NSEC_PER_SEC)),dispatch_get_main_queue(),^{ [NowVIEwControllerdismissVIEwControllerAnimated:NOcompletion:nil]; dict["scanResult"]=cocos2d::LuaValue::stringValue([resultUTF8String]); }); [NowVIEwControllerpresentVIEwController:vcanimated:YEScompletion:nil]; }
其中scanQRCode方法为最终lua掉用oc的方法,在扫描识别出二维码信息之后会将信息传回给lua端。
------------2.6lua掉用oc扫描二维码代码:
如上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方法修改为:
------------3.3扫描二维码界面只支持竖屏ZCZbarVIEwController.mm中增加代码:
------------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。@H_468_3010@一个宽小于高,一个宽大于高,使得4s横屏的时候,6Plus竖屏是对的,而在6Plus上横屏就是乱的。
@H_46_3013@所以后来将两个宏修改为(注意:@H_629_3015@两边一定要带括号@H_468_3010@,防止编译时宏展开后由于 *** 作符优先级导致的运算错误) @H_46_3013@#define WIDTH( ([UIScreen mainScreen].bounds.size.wIDth>[UIScreen mainScreen].bounds.size.height)?[UIScreen mainScreen].bounds.size.wIDth:[UIScreen mainScreen].bounds.size.height )#defineHEIGHT( ([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方法中有句
AVAuthorizationStatusauthStatus = [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
//原生生成二维码
@H_46_3013@http://www.jb51.cc/article/p-zcstxcne-dx.html @H_46_3013@//原生二维码扫描@H_46_3013@http://www.cocoachina.com/ios/20161009/17696.html
@H_46_3013@//zbar下载地址
http://download.csdn.net/download/kid_devil/7552613
//zbarDemo下载地址
http://download.csdn.net/detail/shan1991fei/9474417
//二维码扫描之zXing与zbar的优劣
http://blog.csdn.net/l_215851356/article/details/51898514
总结以上是内存溢出为你收集整理的cocos2dx-lua在ios上实现生成及扫描二维码全部内容,希望文章能够帮你解决cocos2dx-lua在ios上实现生成及扫描二维码所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)