cocos2dx-lua在ios上实现生成及扫描二维码

cocos2dx-lua在ios上实现生成及扫描二维码,第1张

概述首先说明下,我是支持用iOS原生方法实现的。不过扫描二维码原生方法不支持ios7.0之前的设备,所以生成二维码用的原生方法实现,而扫描二维码用zBar sdk实现的(当然也可以用google官方的zXing sdk)。其中zBar中包含生成二维码的方法,而且更多样,我只是喜欢尽量用原生方法来实现。 这里我把所有生成二维码的代码和lua调用的扫描二维码方法都放在了项目->frameworks->ru


首先说明下,我是支持用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中添加代码:

copy /** *根据字符串生成二维码CIImage对象 * *@paramurlString需要生成二维码的字符串 *@return生成的二维码 */ +(CIImage*)creatQRcodeWithUrlstring:(Nsstring*)urlString{ //1.实例化二维码滤镜 CIFilter*filter=[CIFilterfilterWithname:@"CiqrCodeGenerator"]; //2.恢复滤镜的默认属性(因为滤镜有可能保存上一次的属性) [filtersetDefaults]; //3.将字符串转换成NSdata NSData*data=[urlStringdataUsingEnCoding:NSUTF8StringEnCoding]; //4.通过KVO设置滤镜,传入data,将来滤镜就知道要通过传入的数据生成二维码 [filtersetValue:dataforKey:@"inputMessage"]; //5.生成二维码 CIImage*outputimage=[filteroutputimage]; returnoutputimage; } /** *改变图片大小(正方形图片) * *@paramciImage需要改变大小的CIImage对象的图片 *@paramsize图片大小(正方形图片只需要一个数) *@return生成的目标图片 +(UIImage*)changeImageSizeWithCIImage:(CIImage*)ciImageandSize:(CGfloat)size{ CGRectextent=CGRectIntegral(ciImage.extent); CGfloatscale=MIN(size/CGRectGetWIDth(extent),size/CGRectGetHeight(extent)); //创建bitmap; size_twIDth=CGRectGetWIDth(extent)*scale; size_theight=CGRectGetHeight(extent)*scale; CGcolorSpaceRefcs=CGcolorSpaceCreateDeviceGray(); CGContextRefbitmapRef=CGBitmapContextCreate(nil,wIDth,height,8,cs,(CGBitmAPInfo)kCGImageAlphaNone); CIContext*context=[CIContextcontextWithOptions:nil]; CGImageRefbitmAPImage=[contextcreateCGImage:ciImagefromrect:extent]; CGContextSetInterpolationQuality(bitmapRef,kCGInterpolationNone); CGContextScaleCTM(bitmapRef,scale,scale); CGContextDrawImage(bitmapRef,extent,bitmAPImage); //保存bitmap到图片 CGImageRefscaledImage=CGBitmapContextCreateImage(bitmapRef); CGContextRelease(bitmapRef); CGImageRelease(bitmAPImage); return[UIImageimageWithCGImage:scaledImage]; } +(BOol)writeImage:(UIImage*)imagetofileAtPath:(Nsstring*)aPath { if((image==nil)||(aPath==nil)||([aPathisEqualToString:@""])) returnNO; @try NSData*imageData=nil; Nsstring*ext=[aPathpathExtension]; if([extisEqualToString:@"png"]) imageData=UIImagePNGRepresentation(image); else //therest,wewritetojpeg //0.best,1.lost.aboutcompress. imageData=UIImageJPEGRepresentation(image,0); if((imageData==nil)||([imageDatalength]<=0)) [imageDatawritetofile:aPathatomically:YES]; returnYES; @catch(NSException*e) { NSLog(@"createthumbnailexception."); /* *项目-TARGETS-fightGame-mobile-BuildPhases-linkBinaryWithlibrarIEs添加CoreImage.framework voID)createQRCode:(NSDictionary*)info int_callBack=[[infoobjectForKey:@"Listener"]intValue]; Nsstring*qrCodeStr=[infoobjectForKey:@"qrCodeStr"]; CIImage*ciImage=[selfcreatQRcodeWithUrlstring:qrCodeStr]; UIImage*uiImage=[selfchangeImageSizeWithCIImage:ciImageandSize:180]; NSData*imageData=UIImagePNGRepresentation(uiImage); std::stringpath=cocos2d::fileUtils::getInstance()->getWritablePath()+"qrCode.png"; constchar*pathC=path.c_str(); Nsstring*pathN=[NsstringstringWithUTF8String:pathC]; boolisSuccess=[imageDatawritetofile:pathNatomically:YES]; cocos2d::LuaBrIDge::pushLuaFunctionByID(_callBack); cocos2d::LuaValueDictdict; 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方法,并显示

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代码:

copy 版本说明iOS研究院305044955 1.8版本剔除生成二维码文件,使用iOS7原生生成二维码 1.7版本修复了开启相机点击,用户如果点击拒绝,会导致崩溃的问题 1.6版本增加了支持了区别条码和二维码,可以关闭扫描二维码来增加条码扫描速度 1.5版本修正了iOS6下扫描会卡死,增加了iOS7下支持条形码,修改了算法,增加了效率 1.4版本支持iOS8系统,修改了相应UI的适配问题 1.3版本全新支持arm7sarm64全新支持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编译 需要添加AVFoundationCoreMediaCoreVIDeoQuartzCorelibiconv //示例代码 扫描代码 BOol代表是否关闭二维码扫描,专门扫描条形码 ZCZbarVIEwController*vc=[[ZCZbarVIEwControlleralloc]initWithIsQRCode:NOBlock:^(Nsstring*result,BOOlisFinish){ if(isFinish){ NSLog(@"最后的结果%@",result); } }]; [selfpresentVIEwController:vcanimated:YEScompletion:nil]; 生成二维码 [ZCZbarVIEwControllercreateImageWithImageVIEw:imageVIEwString:@"http://www.baIDu.com"Scale:4]; */ #import<UIKit/UIKit.h> #import<AVFoundation/AVFoundation.h> #import"ZbarReaderController.h" #import<CoreImage/CoreImage.h> #defineIOS7[[[UIDevicecurrentDevice]systemVersion]floatValue]>=7 @interfaceZCZbarVIEwController:UIVIEwController<AVCaptureVIDeoDataOutputSampleBufferDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate,ZbarReaderDelegate,AVCaptureMetadataOutputObjectsDelegate> intnum; BOolupOrdown; NSTimer*timer; UIImageVIEw*_line; @property(nonatomic,strong)AVCaptureVIDeoPrevIEwLayer*captureVIDeoPrevIEwLayer; @property(nonatomic,strong)AVCaptureSession*captureSession; BOolisScanning; voID(^ScanResult)(Nsstring*result,BOolisSucceed); @property(nonatomic)BOolisQRCode; //初始化函数 -(ID)initWithIsQRCode:(BOol)isQRCodeBlock:(voID(^)(Nsstring*,87); background-color: inherit; Font-weight: bold;">BOol))a; //正则表达式对扫描结果筛选 +(Nsstring*)zhengze:(Nsstring*)str; //创建二维码 +(voID)createImageWithImageVIEw:(UIImageVIEw*)imageVIEwString:(Nsstring*)strScale:(CGfloat)scale; @end

------------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{ //[email protected][email protected] UIImage*image=[UIImageimagenamed:@"[email protected]"]; 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)]; @[email protected]=[UIcolorwhitecolor]; @[email protected]=[UIcolorclearcolor]; @[email protected]=@"扫一扫"; [self.vIEwaddSubvIEw:@R_301_5979@Label]; //[navImageVIEwaddSubvIEw:@R_301_5979@Label]; UIbutton*button=[UIbuttonbuttonWithType:UIbuttonTypeCustom]; [buttonsetimage:[UIImageimagenamed:@"qrcode_scan_@R_301_5979@[email protected]"]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扫描二维码代码:

copy print("messagescanResult:",message.scanResult) Utils.showTip(message.scanResult) localinfo={Listener=callBack} "scanQRCode",51); Font-family: Arial; Font-size: 0.933rem;">------------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.mmsupportedInterfaceOrIEntations方法修改为:

copy //Forios6,usesupportedInterfaceOrIEntations&shouldautorotateinstead -(NSUInteger)supportedInterfaceOrIEntations{ returnUIInterfaceOrIEntationMaskLandscapeleft|UIInterfaceOrIEntationMaskLandscapeRight; //#ifdef__IPHONE_6_0 //returnUIInterfaceOrIEntationMaskAllButUpsIDeDown; //#endif }

------------3.3扫描二维码界面只支持竖屏ZCZbarVIEwController.mm中增加代码

copy //}

------------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@若编译运行报错,XXXX.o什么什么的问题,则可能是有依赖框架没有导入。

@H_46_3013@-----6.参考链接

//原生生成二维码

@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上实现生成及扫描二维码所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1084953.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-27
下一篇 2022-05-27

发表评论

登录后才能评论

评论列表(0条)

保存