First of all, I support it. iOS The original method is implemented. However, the original method of scanning two-dimensional codes does not support the devices before IOS 7.0, so the original method of generating two-dimensional codes is implemented, while the scanning two-dimensional codes are implemented by zBar sdk (of course, the official zXing SDK of google). Among them, zBar contains methods for generating two-dimensional codes, and there are many more. I just like to use native methods as much as possible.
Here I put all the code that generates the two-dimensional code and the scanning two-dimensional code method called by lua in the project - > Frameworks - > runtime-src - > proj. ios_mac - >. ios -> AppController. h and AppController.mm
zBar sdk and related classes are placed under project - > Frameworks - > runtime - SRC - > proj. ios_mac - > ios.
- 1. Generating two-dimensional code primitively
Add code to 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;
Add code to 1.2AppController.mm:
-
-
-
-
-
-
-
- + (CIImage *)creatQRcodeWithUrlstring:(NSString *)urlString{
-
- CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
-
- [filter setDefaults];
-
- NSData *data = [urlString dataUsingEncoding:NSUTF8StringEncoding];
-
- [filter setValue:data forKey:@"inputMessage"];
-
- CIImage *outputImage = [filter outputImage];
- return outputImage;
- }
-
-
-
-
-
-
-
-
-
- + (UIImage *)changeImageSizeWithCIImage:(CIImage *)ciImage andSize:(CGFloat)size{
- CGRect extent = CGRectIntegral(ciImage.extent);
- CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
-
-
- 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);
-
-
- 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
- {
-
-
- 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;
- }
-
-
-
-
- +(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 method uses oc method for the final lua, saves the generated image under the writable Path of cocos2dx, and saves it as "qrCode.png". Finally, it is taken out at the Lua end and displayed with sprite.
------------------- 1.3lua calls the createQRcode method and displays it
- 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 Adding CoreImage.framework Dependency Framework (2-D code scanning required)
Item - > TARGETS - > Build Phases - > Link Binary With Libraries - > bottom left "+" number, in the search box enter CoreImage.framework, select the matching options.
2.zBar sdk to realize two-dimensional code scanning
Download zBar sdk
The address is given later.
2.2 Decompress the zBarSDK and import the decompressed zBarSDK into the project - > Frameworks - > runtime - SRC - > proj. ios_mac - > ios.
The decompressed zBarSDK directory contains: Headers,libzbar.a,Resources.
If the libzbar.a dependency framework is not automatically added after the project is imported, the dependency framework needs to be added manually (e.g. 1.4).
The new ZCZBarViewController.h and ZCZBarViewController.mm files under the zBarSDK are created and imported into the project. The code is as follows.
Code 2.4ZCZBarViewController.h:
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- #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
Code 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 )
-
- #define HEIGHT ( ([UIScreen mainScreen].bounds.size.width<[UIScreen mainScreen].bounds.size.height)?[UIScreen mainScreen].bounds.size.width:[UIScreen mainScreen].bounds.size.height )
-
-
-
- @implementation ZCZBarViewController
-
- - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
- {
- self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
- if (self) {
-
- }
- 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{
-
-
- 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.clipsToBounds=YES;
- bgImageView.image=image;
- bgImageView.userInteractionEnabled=YES;
- [self.view addSubview:bgImageView];
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- _line = [[UIImageView alloc] initWithFrame:CGRectMake((WIDTH-220)/2, 70, 220, 2)];
- _line.image = [UIImage imageNamed:@"qrcode_scan_light_green.png"];
- [bgImageView addSubview:_line];
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- UILabel*titleLabel=[[UILabel alloc]initWithFrame:CGRectMake(WIDTH/2-32, 20, 64, 44)];
- titleLabel.textColor=[UIColor whiteColor];
- titleLabel.backgroundColor = [UIColor clearColor];
- titleLabel.text=@"Scan";
- [self.view 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
- {
-
-
- BOOL Custom= [UIImagePickerController
- isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
- if (Custom) {
- [self initCapture];
- }else{
- self.view.backgroundColor=[UIColor whiteColor];
- }
- [super viewDidLoad];
- [self createView];
-
-
-
- }
- #Pagma mark Selection Album
- - (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 click Cancel
- - (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];
- }
- #Pagma mark turns on the camera
- - (void)initCapture
- {
-
- if (IOS7) {
- NSString *mediaType = AVMediaTypeVideo;
- AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
-
- if(authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied){
- NSString*str=[NSString stringWithFormat:@"Please set up the system-%@-Open Camera in Camera to Allow Camera Use", [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString*)kCFBundleNameKey]];
- UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Tips" message:str delegate:nil cancelButtonTitle:@"Sure?" 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];
-
-
- if (_isQRCode) {
- _output.metadataObjectTypes =@[AVMetadataObjectTypeQRCode];
-
-
- }else{
- _output.metadataObjectTypes =@[AVMetadataObjectTypeEAN13Code,AVMetadataObjectTypeEAN8Code,AVMetadataObjectTypeCode128Code,AVMetadataObjectTypeQRCode];
- }
-
-
- if (!self.captureVideoPreviewLayer) {
- self.captureVideoPreviewLayer = [AVCaptureVideoPreviewLayer layerWithSession:self.captureSession];
- }
-
- self.captureVideoPreviewLayer.frame = CGRectMake(0, 0, WIDTH, HEIGHT);
- 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") &&
- [UIScreen mainScreen].scale > 1 &&
- [inputDevice
- supportsAVCaptureSessionPreset:AVCaptureSessionPresetiFrame960x540]) {
-
- preset = AVCaptureSessionPresetiFrame960x540;
- }
- if (!preset) {
-
- preset = AVCaptureSessionPresetMedium;
- }
- self.captureSession.sessionPreset = preset;
-
- if (!self.captureVideoPreviewLayer) {
- self.captureVideoPreviewLayer = [AVCaptureVideoPreviewLayer layerWithSession:self.captureSession];
- }
-
- self.captureVideoPreviewLayer.frame = CGRectMake(0, 0, WIDTH, HEIGHT);
- self.captureVideoPreviewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
- [self.view.layer addSublayer: self.captureVideoPreviewLayer];
-
- self.isScanning = YES;
- [self.captureSession startRunning];
-
-
- }
-
-
- }
-
- - (UIImage *) imageFromSampleBuffer:(CMSampleBufferRef) sampleBuffer
- {
- CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);
-
- CVPixelBufferLockBaseAddress(imageBuffer,0);
-
-
- size_t bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer);
-
- size_t width = CVPixelBufferGetWidth(imageBuffer);
- size_t height = CVPixelBufferGetHeight(imageBuffer);
-
-
- CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
- if (!colorSpace)
- {
- NSLog(@"CGColorSpaceCreateDeviceRGB failure");
- return nil;
- }
-
-
- void *baseAddress = CVPixelBufferGetBaseAddress(imageBuffer);
-
- size_t bufferSize = CVPixelBufferGetDataSize(imageBuffer);
-
-
- CGDataProviderRef provider = CGDataProviderCreateWithData(NULL, baseAddress, bufferSize,
- NULL);
-
- CGImageRef cgImage =
- CGImageCreate(width,
- height,
- 8,
- 32,
- bytesPerRow,
- colorSpace,
- kCGImageAlphaNoneSkipFirst | kCGBitmapByteOrder32Little,
- provider,
- NULL,
- true,
- kCGRenderingIntentDefault);
- CGDataProviderRelease(provider);
- CGColorSpaceRelease(colorSpace);
-
-
- UIImage *image = [UIImage imageWithCGImage:cgImage];
-
- return image;
- }
-
- #Pagma mark decodes images
- - (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];
- }
- #Triggered under pragma mark AVCaptureMetadata Output Objects Delegate//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;
-
- 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];
-
- NSString *result1 = [str substringWithRange:resultRange];
- NSLog(@"Results after regular expression%@",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];
-
- }
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- @end
Add code to 2.5 AppController.h:
-
- + (UIViewController *)getCurrentVC;
-
- - (UIViewController *)getPresentedViewController;
-
- +(void)scanQRCode:(NSDictionary *)info;
Add code to 2.5 AppController.mm:
-
- + (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;
- }
-
- - (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];
-
-
-
-
- UIViewController *nowViewController = [self getCurrentVC];
-
- ZCZBarViewController*vc=[[ZCZBarViewController alloc]initWithIsQRCode:NO Block:^(NSString *result, BOOL isFinish) {
- if (isFinish) {
- NSLog(@"Final results%@",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];
- }
The scanQRCode method uses oc method for the final lua. After scanning and identifying the two-dimensional code information, the information will be sent back to the Lua end.
2.6 Lua uses oc to scan two-dimensional code:
- 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 Adding Dependency Framework
As in 1.4 above, scanning two-dimensional codes requires adding frames AVFoundation, CoreMedie, CoreVideo, Quartz Core, libiconv
3. Description of horizontal and vertical screen of scanning interface
If the game interface is horizontal and the two-dimensional code scanning interface is vertical, some operations are needed.
------------- 3.1 Increase vertical screen support
Project - > TARGETS - > General - > Deployment Info - > Device Orientation - > Check Portrait,Landscape Left, Landscape Right.
3.2 Make the Game Interface Supported by Horizontal Screen only
Project - > Frameworks - > runtime - SRC - > proj. ios_mac - > IOS - > RootViewController. mm, the support interface Orientations method is modified as follows:
-
- - (NSUInteger) supportedInterfaceOrientations{
- return UIInterfaceOrientationMaskLandscapeLeft | UIInterfaceOrientationMaskLandscapeRight;
-
-
-
- }
3.3 Scanning 2-D Code Interface Supports Vertical Screen only
Add code to project - > Frameworks - > runtime - SRC - > proj. ios_mac - > IOS - > ZCZBarViewController. mm:
3.4 Modify the view interface width and height to re-adapt
Project - > Frameworks - > runtime - SRC - > proj. ios_mac - > IOS - > ZCZBarViewController. mm Lieutenant General
# The values of define WIDTH and # define HEIGHT are reversed.
About the project - > Frameworks - > runtime - SRC - > proj. ios_mac - > IOS - > ZCZBarViewController. mm #define WIDTH and #define HEIGHT macros
It should have been
#define WIDTH [UIScreen mainScreen].bounds.size.width
#define HEIGHT [UIScreen mainScreen].bounds.size.height
But width and height on iPhone 4S (ios 6.1.3) were 320,480, while width and height on iPhone 6Plus (ios 10.2) were 568,320.
A width is smaller than height, and a width is larger than height, so that when 4s horizontal screen, 6Plus vertical screen is right, while on 6Plus the horizontal screen is messy.
So we later changed the two macros to (note: both sides must be parenthesized to prevent errors caused by operator priority after macro expansion at compile time)
#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 )
Thus, the two values obtained by fixed width are larger than those obtained by fixed width, and the higher values are smaller than those obtained by fixed width. If it's a vertical screen, it's the other way round.
5. Problems encountered
--------------- 5.1 For the initCpture method in ZCZBarViewController.mm
AVAuthorizationStatus authStatus = [AVCaptureDeviceauthorizationStatusForMediaType:mediaType];
Note: This method is only useful for systems above ios7. If it is in ios6 system, it will collapse directly. Moreover, there is no "Settings - Privacy - Camera" item on ios6.
So the judgment of if(IOS7) is added.
5.2 If you encounter an error, Cannot synthesize weak property in file using manual reference counting
Project - > TARGETS - > Build Settings - > Apple LLVM 8.0 - Language - Objective C - > Weak References in Manual Retian Release to YES
5.3 Compiler Error XXXX.o
If compiling and running errors, XXXXXX. o or something, it may be that the dependency framework has not been imported.
6. Reference Links
// Primary Generation of Two-Dimensional Codes
http://blog.csdn.net/zhuming3834/article/details/50832953
// Primary two-dimensional code scanning
http://www.cocoachina.com/ios/20161009/17696.html
// zBar Download Address
http://download.csdn.net/download/kid_devil/7552613
// zBarDemo Download Address
http://download.csdn.net/detail/shan1991fei/9474417
// The Advantages and Disadvantages of Two-Dimensional Code Scanning zXing and zBar
http://blog.csdn.net/l_215851356/article/details/51898514