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

前端之家收集整理的这篇文章主要介绍了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添加代码

  1. //生成二维码
  2. +(CIImage*)creatQRcodeWithUrlstring:(NSString*)urlString;
  3. //改变图片大小(正方形图片)
  4. +(UIImage*)changeImageSizeWithCIImage:(CIImage*)ciImageandSize:(CGFloat)size;
  5. //保存(暂时没用)
  6. +(BOOL)writeImage:(UIImage*)imagetoFileAtPath:(NSString*)aPath;
  7. +(void)createQRCode:(NSDictionary*)info;

------------1.2AppController.mm添加代码

copy
    /**
  1. *根据字符串生成二维码CIImage对象
  2. *
  3. *@paramurlString需要生成二维码的字符串
  4. *@return生成二维码
  5. */
  6. +(CIImage*)creatQRcodeWithUrlstring:(NSString*)urlString{
  7. //1.实例化二维码滤镜
  8. CIFilter*filter=[CIFilterfilterWithName:@"CIQRCodeGenerator"];
  9. //2.恢复滤镜的默认属性(因为滤镜有可能保存上一次的属性)
  10. [filtersetDefaults];
  11. //3.将字符串转换成NSdata
  12. NSData*data=[urlStringdataUsingEncoding:NSUTF8StringEncoding];
  13. //4.通过KVO设置滤镜,传入data,将来滤镜就知道要通过传入的数据生成二维码
  14. [filtersetValue:dataforKey:@"inputMessage"];
  15. //5.生成二维码
  16. CIImage*outputImage=[filteroutputImage];
  17. returnoutputImage;
  18. }
  19. /**
  20. *改变图片大小(正方形图片)
  21. *
  22. *@paramciImage需要改变大小的CIImage对象的图片
  23. *@paramsize图片大小(正方形图片只需要一个数)
  24. *@return生成的目标图片
  25. +(UIImage*)changeImageSizeWithCIImage:(CIImage*)ciImageandSize:(CGFloat)size{
  26. CGRectextent=CGRectIntegral(ciImage.extent);
  27. CGFloatscale=MIN(size/CGRectGetWidth(extent),size/CGRectGetHeight(extent));
  28. //创建bitmap;
  29. size_twidth=CGRectGetWidth(extent)*scale;
  30. size_theight=CGRectGetHeight(extent)*scale;
  31. CGColorSpaceRefcs=CGColorSpaceCreateDeviceGray();
  32. CGContextRefbitmapRef=CGBitmapContextCreate(nil,width,height,8,cs,(CGBitmapInfo)kCGImageAlphaNone);
  33. CIContext*context=[CIContextcontextWithOptions:nil];
  34. CGImageRefbitmapImage=[contextcreateCGImage:ciImagefromRect:extent];
  35. CGContextSetInterpolationQuality(bitmapRef,kCGInterpolationNone);
  36. CGContextScaleCTM(bitmapRef,scale,scale);
  37. CGContextDrawImage(bitmapRef,extent,bitmapImage);
  38. //保存bitmap到图片
  39. CGImageRefscaledImage=CGBitmapContextCreateImage(bitmapRef);
  40. CGContextRelease(bitmapRef);
  41. CGImageRelease(bitmapImage);
  42. return[UIImageimageWithCGImage:scaledImage];
  43. }
  44. +(BOOL)writeImage:(UIImage*)imagetoFileAtPath:(NSString*)aPath
  45. {
  46. if((image==nil)||(aPath==nil)||([aPathisEqualToString:@""]))
  47. returnNO;
  48. @try
  49. NSData*imageData=nil;
  50. NSString*ext=[aPathpathExtension];
  51. if([extisEqualToString:@"png"])
  52. imageData=UIImagePNGRepresentation(image);
  53. else
  54. //therest,wewritetojpeg
  55. //0.best,1.lost.aboutcompress.
  56. imageData=UIImageJPEGRepresentation(image,0);
  57. if((imageData==nil)||([imageDatalength]<=0))
  58. [imageDatawriteToFile:aPathatomically:YES];
  59. returnYES;
  60. @catch(NSException*e)
  61. {
  62. NSLog(@"createthumbnailexception.");
  63. /*
  64. *项目-TARGETS-fightGame-mobile-BuildPhases-LinkBinaryWithLibraries添加CoreImage.framework
  65. void)createQRCode:(NSDictionary*)info
  66. int_callBack=[[infoobjectForKey:@"listener"]intValue];
  67. NSString*qrCodeStr=[infoobjectForKey:@"qrCodeStr"];
  68. CIImage*ciImage=[selfcreatQRcodeWithUrlstring:qrCodeStr];
  69. UIImage*uiImage=[selfchangeImageSizeWithCIImage:ciImageandSize:180];
  70. NSData*imageData=UIImagePNGRepresentation(uiImage);
  71. std::stringpath=cocos2d::FileUtils::getInstance()->getWritablePath()+"qrCode.png";
  72. constchar*pathC=path.c_str();
  73. NSString*pathN=[NSStringstringWithUTF8String:pathC];
  74. boolisSuccess=[imageDatawriteToFile:pathNatomically:YES];
  75. cocos2d::LuaBridge::pushLuaFunctionById(_callBack);
  76. cocos2d::LuaValueDictdict;
  77. dict["isSuccess"]=cocos2d::LuaValue::booleanValue(isSuccess);
  78. cocos2d::LuaBridge::getStack()->pushLuaValueDict(dict);
  79. cocos2d::LuaBridge::getStack()->executeFunction(1);
  80. cocos2d::LuaBridge::releaseLuaFunctionById(_callBack);
  81. }

其中createQRcode方法为最终lua掉用oc的方法,将生成图片存到cocos2dx的writablePath下,并保存为"qrCode.png"。最后在lua端取出用sprite显示

------------1.3lua调用createQRcode方法,并显示

copy

    localcallBack=function(message)
  1. localfilePath=cc.FileUtils:getInstance():getWritablePath()
  2. filePath=filePath.."qrCode.png"
  3. localrect=cc.rect(0,180,180)
  4. localsprite=cc.Sprite:create()
  5. sprite:initWithFile(filePath,rect)
  6. sprite:setPosition(300,300)
  7. self:addChild(sprite)
  8. end
  9. localinfo={listener=callBack,qrCodeStr="https://www.baidu.com/"}
  10. 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. 1.8版本剔除生成二维码文件,使用iOS7原生生成二维码
  2. 1.7版本修复了开启相机点击,用户如果点击拒绝,会导致崩溃的问题
  3. 1.6版本增加支持了区别条码和二维码,可以关闭扫描二维码增加条码扫描速度
  4. 1.5版本修正了iOS6下扫描会卡死,增加了iOS7下支持条形码,修改了算法,增加了效率
  5. 1.4版本支持iOS8系统,修改了相应UI的适配问题
  6. 1.3版本全新支持arm7sarm64全新支持ARC
  7. 1.2版本ZC封装的ZBar二维码SDK
  8. 1、更新类名从CustomViewController更改为ZCZBarViewController
  9. 2、删除掉代理的相关代码
  10. 1.1版本ZC封装的ZBar二维码SDK~
  11. 1、增加block回调
  12. 2、取消代理
  13. 3、增加适配IOS7(ios7在AVFoundation中增加了扫描二维码功能
  14. 1.0版本ZC封装的ZBar二维码SDK~1.0版本初始建立
  15. 二维码编译顺序
  16. Zbar编译
  17. 需要添加AVFoundationCoreMediaCoreVideoQuartzCorelibiconv
  18. //示例代码
  19. 扫描代码
  20. BOOL代表是否关闭二维码扫描,专门扫描条形码
  21. ZCZBarViewController*vc=[[ZCZBarViewControlleralloc]initWithIsQRCode:NOBlock:^(NSString*result,BOOLisFinish){
  22. if(isFinish){
  23. NSLog(@"最后的结果%@",result);
  24. }
  25. }];
  26. [selfpresentViewController:vcanimated:YEScompletion:nil];
  27. 生成二维码
  28. [ZCZBarViewControllercreateImageWithImageView:imageViewString:@"http://www.baidu.com"Scale:4];
  29. */
  30. #import<UIKit/UIKit.h>
  31. #import<AVFoundation/AVFoundation.h>
  32. #import"ZBarReaderController.h"
  33. #import<CoreImage/CoreImage.h>
  34. #defineIOS7[[[UIDevicecurrentDevice]systemVersion]floatValue]>=7
  35. @interfaceZCZBarViewController:UIViewController<AVCaptureVideoDataOutputSampleBufferDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate,ZBarReaderDelegate,AVCaptureMetadataOutputObjectsDelegate>
  36. intnum;
  37. BOOLupOrdown;
  38. NSTimer*timer;
  39. UIImageView*_line;
  40. @property(nonatomic,strong)AVCaptureVideoPreviewLayer*captureVideoPreviewLayer;
  41. @property(nonatomic,strong)AVCaptureSession*captureSession;
  42. BOOLisScanning;
  43. void(^ScanResult)(NSString*result,BOOLisSucceed);
  44. @property(nonatomic)BOOLisQRCode;
  45. //初始化函数
  46. -(id)initWithIsQRCode:(BOOL)isQRCodeBlock:(void(^)(NSString*,87); background-color: inherit; font-weight: bold;">BOOL))a;
  47. //正则表达式对扫描结果筛选
  48. +(NSString*)zhengze:(NSString*)str;
  49. //创建二维码
  50. +(void)createImageWithImageView:(UIImageView*)imageViewString:(NSString*)strScale:(CGFloat)scale;
  51. @end

------------2.4ZCZBarViewController.mm代码
copy

    #import"ZCZBarViewController.h"
  1. #import<AssetsLibrary/AssetsLibrary.h>
  2. @interfaceZCZBarViewController()
  3. @end
  4. #defineWIDTH(([UIScreenmainScreen].bounds.size.width>[UIScreenmainScreen].bounds.size.height)?[UIScreenmainScreen].bounds.size.width:[UIScreenmainScreen].bounds.size.height)
  5. //[UIScreenmainScreen].bounds.size.width
  6. #defineHEIGHT(([UIScreenmainScreen].bounds.size.width<[UIScreenmainScreen].bounds.size.height)?[UIScreenmainScreen].bounds.size.width:[UIScreenmainScreen].bounds.size.height)
  7. //[UIScreenmainScreen].bounds.size.height
  8. @implementationZCZBarViewController
  9. -(id)initWithNibName:(NSString*)nibNameOrNilbundle:(NSBundle*)nibBundleOrNil
  10. self=[superinitWithNibName:nibNameOrNilbundle:nibBundleOrNil];
  11. if(self){
  12. //Custominitialization
  13. returnself;
  14. BOOL))a
  15. if(self=[superinit]){
  16. self.ScanResult=a;
  17. self.isQRCode=isQRCode;
  18. -(void)createView{
  19. //qrcode_scan_bg_Green_iphone5@2x.pngqrcode_scan_bg_Green@2x.png
  20. UIImage*image=[UIImageimageNamed:@"qrcode_scan_bg_Green@2x.png"];
  21. floatcapWidth=image.size.width/2;
  22. floatcapHeight=image.size.height/2;
  23. image=[imagestretchableImageWithLeftCapWidth:capWidthtopCapHeight:capHeight];
  24. UIImageView*bgImageView=[[UIImageViewalloc]initWithFrame:CGRectMake(0,64,WIDTH,HEIGHT-64)];
  25. //bgImageView.contentMode=UIViewContentModeTop;
  26. bgImageView.clipsToBounds=YES;
  27. bgImageView.image=image;
  28. bgImageView.userInteractionEnabled=YES;
  29. [self.viewaddSubview:bgImageView];
  30. //UILabel*label=[[UILabelalloc]initWithFrame:CGRectMake(0,bgImageView.frame.size.height-140,40)];
  31. //label.text=@"将取景框对准二维码,即可自动扫描。";
  32. //label.textColor=[UIColorwhiteColor];
  33. //label.textAlignment=NSTextAlignmentCenter;
  34. //label.lineBreakMode=NSLineBreakByWordWrapping;
  35. //label.numberOfLines=2;
  36. //label.font=[UIFontsystemFontOfSize:12];
  37. //label.backgroundColor=[UIColorclearColor];
  38. //[bgImageViewaddSubview:label];
  39. _line=[[UIImageViewalloc]initWithFrame:CGRectMake((WIDTH-220)/2,70,220,2)];
  40. _line.image=[UIImageimageNamed:@"qrcode_scan_light_green.png"];
  41. [bgImageViewaddSubview:_line];
  42. ////下方相册
  43. //UIImageView*scanImageView=[[UIImageViewalloc]initWithFrame:CGRectMake(0,HEIGHT-100,100)];
  44. //scanImageView.image=[UIImageimageNamed:@"qrcode_scan_bar.png"];
  45. //scanImageView.userInteractionEnabled=YES;
  46. //[self.viewaddSubview:scanImageView];
  47. //NSArray*unSelectImageNames=@[@"qrcode_scan_btn_photo_nor.png",@"qrcode_scan_btn_flash_nor.png",@"qrcode_scan_btn_myqrcode_nor.png"];
  48. //NSArray*selectImageNames=@[@"qrcode_scan_btn_photo_down.png",@"qrcode_scan_btn_flash_down.png",@"qrcode_scan_btn_myqrcode_down.png"];
  49. //
  50. //for(inti=0;i<unSelectImageNames.count;i++){
  51. //UIButton*button=[UIButtonbuttonWithType:UIButtonTypeCustom];
  52. //[buttonsetImage:[UIImageimageNamed:unSelectImageNames[i]]forState:UIControlStateNormal];
  53. //[buttonsetImage:[UIImageimageNamed:selectImageNames[i]]forState:UIControlStateHighlighted];
  54. //button.frame=CGRectMake(WIDTH/3*i,WIDTH/3,100);
  55. //[scanImageViewaddSubview:button];
  56. //if(i==0){
  57. //[buttonaddTarget:selfaction:@selector(pressPhotoLibraryButton:)forControlEvents:UIControlEventTouchUpInside];
  58. //}
  59. //if(i==1){
  60. //[buttonaddTarget:selfaction:@selector(flashLightClick)forControlEvents:UIControlEventTouchUpInside];
  61. //}
  62. //if(i==2){
  63. //button.hidden=YES;
  64. //假导航
  65. //UIImageView*navImageView=[[UIImageViewalloc]initWithFrame:CGRectMake(0,64)];
  66. //navImageView.image=[UIImageimageNamed:@"qrcode_scan_bar.png"];
  67. //navImageView.userInteractionEnabled=YES;
  68. //[self.viewaddSubview:navImageView];
  69. UILabel*titleLabel=[[UILabelalloc]initWithFrame:CGRectMake(WIDTH/2-32,20,44)];
  70. titleLabel.textColor=[UIColorwhiteColor];
  71. titleLabel.backgroundColor=[UIColorclearColor];
  72. titleLabel.text=@"扫一扫";
  73. [self.viewaddSubview:titleLabel];
  74. //[navImageViewaddSubview:titleLabel];
  75. UIButton*button=[UIButtonbuttonWithType:UIButtonTypeCustom];
  76. [buttonsetImage:[UIImageimageNamed:@"qrcode_scan_titlebar_back_pressed@2x.png"]forState:UIControlStateHighlighted];
  77. [buttonsetImage:[UIImageimageNamed:@"qrcode_scan_titlebar_back_nor.png"]forState:UIControlStateNormal];
  78. [buttonsetFrame:CGRectMake(10,10,48,48)];
  79. [buttonaddTarget:selfaction:@selector(pressCancelButton:)forControlEvents:UIControlEventTouchUpInside];
  80. [self.viewaddSubview:button];
  81. timer=[NSTimerscheduledTimerWithTimeInterval:2target:selfselector:@selector(animation1)userInfo:nilrepeats:YES];
  82. -(void)animation1
  83. [UIViewanimateWithDuration:2animations:^{
  84. _line.frame=CGRectMake((WIDTH-220)/2,70+HEIGHT-310,2);
  85. }completion:^(BOOLfinished){
  86. _line.frame=CGRectMake((WIDTH-220)/2,2);
  87. }];
  88. //开启关闭闪光灯
  89. void)flashLightClick{
  90. AVCaptureDevice*device=[AVCaptureDevicedefaultDeviceWithMediaType:AVMediaTypeVideo];
  91. if(device.torchMode==AVCaptureTorchModeOff){
  92. //闪光灯开启
  93. [devicelockForConfiguration:nil];
  94. [devicesetTorchMode:AVCaptureTorchModeOn];
  95. }else{
  96. //闪光灯关闭
  97. [devicesetTorchMode:AVCaptureTorchModeOff];
  98. void)viewDidLoad
  99. //相机界面的定制在self.view上加载即可
  100. BOOLCustom=[UIImagePickerController
  101. isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];//判断摄像头是否能用
  102. if(Custom){
  103. [selfinitCapture];//启动摄像头
  104. self.view.backgroundColor=[UIColorwhiteColor];
  105. [superviewDidLoad];
  106. [selfcreateView];
  107. #pragmamark选择相册
  108. void)pressPhotoLibraryButton:(UIButton*)button
  109. {if(timer){
  110. [timerinvalidate];
  111. timer=nil;
  112. num=0;
  113. upOrdown=NO;
  114. UIImagePickerController*picker=[[UIImagePickerControlleralloc]init];
  115. picker.allowsEditing=YES;
  116. picker.delegate=self;
  117. picker.sourceType=UIImagePickerControllerSourceTypePhotoLibrary;
  118. [selfpresentViewController:pickeranimated:YEScompletion:^{
  119. self.isScanning=NO;
  120. [self.captureSessionstopRunning];
  121. }];
  122. #pragmamark点击取消
  123. void)pressCancelButton:(UIButton*)button
  124. self.isScanning=NO;
  125. [self.captureSessionstopRunning];
  126. self.ScanResult(nil,NO);
  127. if(timer){
  128. [timerinvalidate];
  129. timer=nil;
  130. num=0;
  131. upOrdown=NO;
  132. [selfdismissViewControllerAnimated:YEScompletion:nil];
  133. #pragmamark开启相机
  134. void)initCapture
  135. //ios6上也没有“设置--隐私--相机”那一项
  136. if(IOS7){
  137. NSString*mediaType=AVMediaTypeVideo;
  138. AVAuthorizationStatusauthStatus=[AVCaptureDeviceauthorizationStatusForMediaType:mediaType];
  139. if(authStatus==AVAuthorizationStatusRestricted||authStatus==AVAuthorizationStatusDenied){
  140. NSString*str=[NSStringstringWithFormat:@"请在系统设置-%@-相机中打开允许使用相机",[[[NSBundlemainBundle]infoDictionary]objectForKey:(NSString*)kcfBundleNameKey]];
  141. UIAlertView*alert=[[UIAlertViewalloc]initWithTitle:@"提示"message:strdelegate:nilcancelButtonTitle:@"确定"otherButtonTitles:nil,nil];
  142. [alertshow];
  143. return;
  144. self.captureSession=[[AVCaptureSessionalloc]init];
  145. AVCaptureDevice*inputDevice=[AVCaptureDevicedefaultDeviceWithMediaType:AVMediaTypeVideo];
  146. AVCaptureDeviceInput*captureInput=[AVCaptureDeviceInputdeviceInputWithDevice:inputDeviceerror:nil];
  147. [self.captureSessionaddInput:captureInput];
  148. AVCaptureVideoDataOutput*captureOutput=[[AVCaptureVideoDataOutputalloc]init];
  149. captureOutput.alwaysDiscardsLateVideoFrames=YES;
  150. if(IOS7){
  151. AVCaptureMetadataOutput*_output=[[AVCaptureMetadataOutputalloc]init];
  152. [_outputsetMetadataObjectsDelegate:selfqueue:dispatch_get_main_queue()];
  153. [self.captureSessionsetSessionPreset:AVCaptureSessionPresetHigh];
  154. [self.captureSessionaddOutput:_output];
  155. //在这里修改了,可以让原生兼容二维码和条形码,无需在使用Zbar
  156. if(_isQRCode){
  157. _output.MetadataObjectTypes=@[AVMetadataObjectTypeQRCode];
  158. }else{
  159. _output.MetadataObjectTypes=@[AVMetadataObjectTypeEAN13Code,AVMetadataObjectTypeEAN8Code,AVMetadataObjectTypeCode128Code,AVMetadataObjectTypeQRCode];
  160. if(!self.captureVideoPreviewLayer){
  161. self.captureVideoPreviewLayer=[AVCaptureVideoPreviewLayerlayerWithSession:self.captureSession];
  162. //NSLog(@"prev%p%@",self.prevLayer,self.prevLayer);
  163. self.captureVideoPreviewLayer.frame=CGRectMake(0,HEIGHT);//self.view.bounds;
  164. self.captureVideoPreviewLayer.videoGravity=AVLayerVideoGravityResizeAspectFill;
  165. [self.view.layeraddSublayer:self.captureVideoPreviewLayer];
  166. self.isScanning=YES;
  167. [self.captureSessionstartRunning];
  168. dispatch_queue_tqueue=dispatch_queue_create("myQueue",NULL);
  169. [captureOutputsetSampleBufferDelegate:selfqueue:queue];
  170. NSString*key=(NSString*)kCVPixelBufferPixelFormatTypeKey;
  171. NSNumber*value=[NSNumbernumberWithUnsignedInt:kCVPixelFormatType_32BGRA];
  172. NSDictionary*videoSettings=[NSDictionarydictionaryWithObject:valueforKey:key];
  173. [captureOutputsetVideoSettings:videoSettings];
  174. [self.captureSessionaddOutput:captureOutput];
  175. NSString*preset=0;
  176. if(NSClassFromString(@"NSOrderedSet")&&//Proxyfor"isthisiOS5"...
  177. [UIScreenmainScreen].scale>1&&
  178. [inputDevice
  179. supportsAVCaptureSessionPreset:AVCaptureSessionPresetiFrame960x540]){
  180. //NSLog(@"960");
  181. preset=AVCaptureSessionPresetiFrame960x540;
  182. if(!preset){
  183. //NSLog(@"MED");
  184. preset=AVCaptureSessionPresetMedium;
  185. self.captureSession.sessionPreset=preset;
  186. if(!self.captureVideoPreviewLayer){
  187. self.captureVideoPreviewLayer=[AVCaptureVideoPreviewLayerlayerWithSession:self.captureSession];
  188. self.captureVideoPreviewLayer.frame=CGRectMake(0,0); background-color: inherit;">//self.view.bounds;
  189. self.captureVideoPreviewLayer.videoGravity=AVLayerVideoGravityResizeAspectFill;
  190. [self.view.layeraddSublayer:self.captureVideoPreviewLayer];
  191. self.isScanning=YES;
  192. [self.captureSessionstartRunning];
  193. -(UIImage*)imageFromSampleBuffer:(CMSampleBufferRef)sampleBuffer
  194. CVImageBufferRefimageBuffer=CMSampleBufferGetImageBuffer(sampleBuffer);
  195. //Lockthebaseaddressofthepixelbuffer
  196. CVPixelBufferLockBaseAddress(imageBuffer,0); background-color: inherit;">//Getthenumberofbytesperrowforthepixelbuffer
  197. size_tbytesPerRow=CVPixelBufferGetBytesPerRow(imageBuffer);
  198. //Getthepixelbufferwidthandheight
  199. size_twidth=CVPixelBufferGetWidth(imageBuffer);
  200. size_theight=CVPixelBufferGetHeight(imageBuffer);
  201. //Createadevice-dependentRGBcolorspace
  202. CGColorSpaceRefcolorSpace=CGColorSpaceCreateDeviceRGB();
  203. if(!colorSpace)
  204. NSLog(@"CGColorSpaceCreateDeviceRGBfailure");
  205. returnnil;
  206. //Getthebaseaddressofthepixelbuffer
  207. void*baseAddress=CVPixelBufferGetBaseAddress(imageBuffer);
  208. //Getthedatasizeforcontiguousplanesofthepixelbuffer.
  209. size_tbufferSize=CVPixelBufferGetDataSize(imageBuffer);
  210. //CreateaQuartzdirect-accessdataproviderthatusesdatawesupply
  211. CGDataProviderRefprovider=CGDataProviderCreateWithData(NULL,baseAddress,bufferSize,
  212. NULL);
  213. //Createabitmapimagefromdatasuppliedbyourdataprovider
  214. CGImageRefcgImage=
  215. CGImageCreate(width,248); line-height: 18px; padding: 0px 3px 0px 10px !important; list-style-position: outside !important;">height,
  216. 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,
  217. kCGRenderingIntentDefault);
  218. CGDataProviderRelease(provider);
  219. CGColorSpaceRelease(colorSpace);
  220. //CreateandreturnanimageobjectrepresentingthespecifiedQuartzimage
  221. UIImage*image=[UIImageimageWithCGImage:cgImage];
  222. returnimage;
  223. #pragmamark对图像进行解码
  224. void)decodeImage:(UIImage*)image
  225. ZBarSymbol*symbol=nil;
  226. ZBarReaderController*read=[ZBarReaderControllernew];
  227. read.readerDelegate=self;
  228. CGImageRefcgImageRef=image.CGImage;
  229. for(symbolin[readscanImage:cgImageRef])break;
  230. if(symbol!=nil){
  231. self.ScanResult(symbol.data,YES);
  232. [selfdismissViewControllerAnimated:YEScompletion:nil];
  233. timer=[NSTimerscheduledTimerWithTimeInterval:.02target:selfselector:@selector(animation1)userInfo:nilrepeats:YES];
  234. #pragmamark-AVCaptureVideoDataOutputSampleBufferDelegate
  235. void)captureOutput:(AVCaptureOutput*)captureOutputdidOutputSampleBuffer:(CMSampleBufferRef)sampleBufferfromConnection:(AVCaptureConnection*)connection
  236. UIImage*image=[selfimageFromSampleBuffer:sampleBuffer];
  237. [selfdecodeImage:image];
  238. #pragmamarkAVCaptureMetadataOutputObjectsDelegate//IOS7下触发
  239. void)captureOutput:(AVCaptureOutput*)captureOutputdidOutputMetadataObjects:(NSArray*)MetadataObjectsfromConnection:(AVCaptureConnection*)connection
  240. if(MetadataObjects.count>0)
  241. AVMetadataMachineReadableCodeObject*MetadataObject=[MetadataObjectsobjectAtIndex:0];
  242. 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
  243. void)imagePickerController:(UIImagePickerController*)pickerdidFinishPickingMediaWithInfo:(NSDictionary*)info
  244. UIImage*image=[infoobjectForKey:@"UIImagePickerControllerEditedImage"];
  245. [selfdismissViewControllerAnimated:YEScompletion:^{[selfdecodeImage:image];}];
  246. void)imagePickerControllerDidCancel:(UIImagePickerController*)picker
  247. [selfdismissViewControllerAnimated:YEScompletion:^{
  248. #pragmamark-DecoderDelegate
  249. +(NSString*)zhengze:(NSString*)str
  250. NSError*error;
  251. //http+:[^\\s]*这是检测网址的正则表达式
  252. NSRegularExpression*regex=[NSRegularExpressionregularExpressionWithPattern:@"http+:[^\\s]*"options:0error:&error];//筛选
  253. if(regex!=nil){
  254. NSTextCheckingResult*firstMatch=[regexfirstMatchInString:stroptions:0range:NSMakeRange(0,[strlength])];
  255. if(firstMatch){
  256. NSRangeresultRange=[firstMatchrangeAtIndex:0];
  257. //从urlString中截取数据
  258. NSString*result1=[strsubstringWithRange:resultRange];
  259. NSLog(@"正则表达后的结果%@",result1);
  260. returnresult1;
  261. returnnil;
  262. void)createImageWithImageView:(UIImageView*)imageViewString:(NSString*)strScale:(CGFloat)scale{
  263. [filtersetDefaults];
  264. NSData*data=[strdataUsingEncoding:NSUTF8StringEncoding];
  265. CIContext*context=[CIContextcontextWithOptions:nil];
  266. CGImageRefcgImage=[contextcreateCGImage:outputImage
  267. fromRect:[outputImageextent]];
  268. UIImage*image=[UIImageimageWithCGImage:cgImage
  269. scale:1.0
  270. orientation:UIImageOrientationUp];
  271. UIImage*resized=nil;
  272. CGFloatwidth=image.size.width*scale;
  273. CGFloatheight=image.size.height*scale;
  274. UIGraphicsBeginImageContext(CGSizeMake(width,height));
  275. CGContextRefcontext1=UIGraphicsGetCurrentContext();
  276. CGContextSetInterpolationQuality(context1,kCGInterpolationNone);
  277. [imagedrawInRect:CGRectMake(0,-50,height)];
  278. resized=UIGraphicsGetImageFromCurrentImageContext();
  279. UIGraphicsEndImageContext();
  280. imageView.image=resized;
  281. CGImageRelease(cgImage);
  282. void)didReceiveMemoryWarning
  283. [superdidReceiveMemoryWarning];
  284. //DispoSEOfanyresourcesthatcanberecreated.
  285. /*
  286. #pragmamark-Navigation
  287. //Inastoryboard-basedapplication,youwilloftenwanttodoalittlepreparationbeforenavigation
  288. -(void)prepareForSegue:(UIStoryboardSegue*)seguesender:(id)sender
  289. {
  290. //Getthenewviewcontrollerusing[seguedestinationViewController].
  291. //Passtheselectedobjecttothenewviewcontroller.
  292. }
  293. ////支持旋转
  294. //-(BOOL)shouldAutorotate{
  295. //returnNO;
  296. ////支持的方向
  297. //-(UIInterfaceOrientationMask)supportedInterfaceOrientations{
  298. //returnUIInterfaceOrientationMaskPortrait;
  299. @end

------------2.5AppController.h中添加代码

copy

    //获取当前正在显示的ViewController
  1. +(UIViewController*)getCurrentVC;
  2. //获取当前屏幕中present出来的viewcontroller。
  3. -(UIViewController*)getPresentedViewController;
  4. //扫描二维码
  5. void)scanQRCode:(NSDictionary*)info;

------------2.5AppController.mm中添加代码
copy

    +(UIViewController*)getCurrentVC
  1. UIViewController*result=nil;
  2. UIWindow*window=[[UIApplicationsharedApplication]keyWindow];
  3. if(window.windowLevel!=UIWindowLevelNormal)
  4. NSArray*windows=[[UIApplicationsharedApplication]windows];
  5. for(UIWindow*tmpWininwindows)
  6. if(tmpWin.windowLevel==UIWindowLevelNormal)
  7. window=tmpWin;
  8. break;
  9. UIView*frontView=[[windowsubviews]objectAtIndex:0];
  10. idnextResponder=[frontViewnextResponder];
  11. if([nextResponderisKindOfClass:[UIViewControllerclass]])
  12. result=nextResponder;
  13. result=window.rootViewController;
  14. returnresult;
  15. //获取当前屏幕中present出来的viewcontroller。
  16. -(UIViewController*)getPresentedViewController
  17. UIViewController*appRootVC=[UIApplicationsharedApplication].keyWindow.rootViewController;
  18. UIViewController*topVC=appRootVC;
  19. if(topVC.presentedViewController){
  20. topVC=topVC.presentedViewController;
  21. returntopVC;
  22. void)scanQRCode:(NSDictionary*)info
  23. //SGScanningQRCodeVC*scanningQRCodeVC=[[SGScanningQRCodeVCalloc]init];
  24. //[scanningQRCodeVCsetupScanningQRCode];
  25. UIViewController*nowViewController=[selfgetCurrentVC];
  26. ZCZBarViewController*vc=[[ZCZBarViewControlleralloc]initWithIsQRCode:NOBlock:^(NSString*result,BOOLisFinish){
  27. if(isFinish){
  28. NSLog(@"最后的结果%@",result);
  29. UIViewController*nowViewController=[selfgetCurrentVC];
  30. dispatch_after(dispatch_time(DISPATCH_TIME_NOW,(int64_t)(0.02*NSEC_PER_SEC)),dispatch_get_main_queue(),^{
  31. [nowViewControllerdismissViewControllerAnimated:NOcompletion:nil];
  32. dict["scanResult"]=cocos2d::LuaValue::stringValue([resultUTF8String]);
  33. });
  34. [nowViewControllerpresentViewController:vcanimated:YEScompletion:nil];
  35. }

其中scanQRCode方法为最终lua掉用oc的方法,在扫描识别出二维码信息之后会将信息传回给lua端。

------------2.6lua掉用oc扫描二维码代码

copy
    print("messagescanResult:",message.scanResult)
  1. Utils.showTip(message.scanResult)
  2. localinfo={listener=callBack}
  3. "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
    1. -(NSUInteger)supportedInterfaceOrientations{
    2. returnUIInterfaceOrientationMaskLandscapeLeft|UIInterfaceOrientationMaskLandscapeRight;
    3. //#ifdef__IPHONE_6_0
    4. //returnUIInterfaceOrientationMaskAllButUpsideDown;
    5. //#endif
    6. }

    ------------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_43_3010@一个宽小于高,一个宽大于高,使得4s横屏的时候,6Plus竖屏是对的,而在6Plus上横屏就是乱的。

    @H_541_3013@所以后来将两个宏修改为(注意:@H_480_3015@两边一定要带括号@H_43_3010@,防止编译时宏展开后由于操作符优先级导致的运算错误)

    @H_541_3013@#define WIDTH( ([UIScreen mainScreen].bounds.size.width>[UIScreen mainScreen].bounds.size.height)?[UIScreen mainScreen].bounds.size.width:[UIScreen mainScreen].bounds.size.height )@H_404_3026@
    #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_541_3013@若编译运行报错,XXXX.o什么什么的问题,则可能是有依赖框架没有导入。

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

    //原生生成二维码

    @H_541_3013@http://www.jb51.cc/article/p-zcstxcne-dx.html

    @H_541_3013@//原生二维码扫描

    @H_541_3013@http://www.cocoachina.com/ios/20161009/17696.html

    @H_541_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

    原文链接:https://www.f2er.com/cocos2dx/338382.html

    猜你在找的Cocos2d-x相关文章