iOS 二维码生成及扫码详解及实例代码
iOS二维码生成及扫码
现在越来越多的应用加入二维码相关的业务,在iOS开发市场上很多开发人员都在使用第三方的扫码与生成二维码的控件,个人认为此类的第三方控件识别度不高。最近正好整理新框架的事情,研究了一下。具体代码如下
生成二维码代码
/** *@author半饱,15-12-18 * *@brief生成二维码图片 * *@paramcode生成二维码图片内容 *@paramwidth二维码图片宽度 *@paramheight二维码图片高度 * *@return返回UIImage对象 */ -(UIImage*)generateQRCode:(NSString*)codewidth:(CGFloat)widthheight:(CGFloat)height{ CIImage*qrcodeImage; NSData*data=[codedataUsingEncoding:NSISOLatin1StringEncodingallowLossyConversion:false]; CIFilter*filter=[CIFilterfilterWithName:@"CIQRCodeGenerator"]; [filtersetValue:dataforKey:@"inputMessage"]; [filtersetValue:@"H"forKey:@"inputCorrectionLevel"]; qrcodeImage=[filteroutputImage]; CGFloatscaleX=width/qrcodeImage.extent.size.width; CGFloatscaleY=height/qrcodeImage.extent.size.height; CIImage*transformedImage=[qrcodeImageimageByApplyingTransform:CGAffineTransformScale(CGAffineTransformIdentity,scaleX,scaleY)]; return[UIImageimageWithCIImage:transformedImage]; }
扫描二维码代码
#import<AVFoundation/AVFoundation.h> staticconstfloatlightWidth=240.f; staticconstfloatlightHeight=240.f; staticconstfloatcrossLineWidth=2.f; staticconstfloatcrossLineHeight=15.f; @interfaceBBScanCodeViewController()<AVCaptureMetadataOutputObjectsDelegate>{ floatleftWith; floattopHeight; } @property(strong,nonatomic)AVCaptureDevice*captureDevice; @property(strong,nonatomic)AVCaptureDeviceInput*captureInput; @property(strong,nonatomic)AVCaptureMetadataOutput*captureOutput; @property(strong,nonatomic)AVCaptureSession*captureSession; @property(strong,nonatomic)AVCaptureVideoPreviewLayer*capturePreview; @property(strong,nonatomic)UIButton*flashLightBtn; @property(strong,nonatomic)UIImageView*lineImageView; @end @implementationBBScanCodeViewController @synthesizecaptureDevice=_captureDevice; @synthesizecaptureInput=_captureInput; @synthesizecaptureOutput=_captureOutput; @synthesizecapturePreview=_capturePreview; @synthesizecaptureSession=_captureSession; @synthesizedelegate=_delegate; @synthesizeisRectScan=_isRectScan; @synthesizelineImageView=_lineImageView; @synthesizeflashLightBtn=_flashLightBtn; -(void)viewDidLoad{ [superviewDidLoad]; self.isShowNavigationItem=YES; CGRectscreenRect=[UIScreenmainScreen].bounds; leftWith=(screenRect.size.width-lightWidth)/2; topHeight=(screenRect.size.height-lightHeight)/2; #if!TARGET_IPHONE_SIMULATOR [selfinitScanCode]; #endif [selfinitLayer]; [selfinitViewControl]; [[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(willResignActiveNotification)name:UIApplicationWillResignActiveNotificationobject:nil];//监听是否触发home键挂起程序. [[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(didBecomeActiveNotification)name:UIApplicationDidBecomeActiveNotificationobject:nil];//监听是否重新进入程序程序. } -(void)viewWillDisappear:(BOOL)animated{ [selfstopScanCode]; [superviewWillDisappear:animated]; } -(void)willResignActiveNotification{ _flashLightBtn.selected=NO; } -(void)didBecomeActiveNotification{ } //加载界面上的控件,如:加上闪光灯按钮等 -(void)initViewControl{ @autoreleasepool{ _flashLightBtn=[UIButtonbuttonWithType:UIButtonTypeCustom]; [_flashLightBtnsetImage:[UIImageimageNamed:@"OpenFlashLight.png"]forState:UIControlStateNormal]; [_flashLightBtnsetImage:[UIImageimageNamed:@"CloseFlashLight.png"]forState:UIControlStateSelected]; _flashLightBtn.frame=CGRectMake(leftWith,80.f,30.f,30.f); [_flashLightBtnaddTarget:selfaction:@selector(systemFlashLight)forControlEvents:UIControlEventTouchUpInside]; [self.viewaddSubview:_flashLightBtn]; _lineImageView=[[UIImageViewalloc]initWithImage:nil]; _lineImageView.backgroundColor=[UIColorgreenColor]; _lineImageView.frame=CGRectMake(leftWith,topHeight,lightWidth,2); [self.viewaddSubview:_lineImageView]; [selfscanLineAnimation]; } } -(void)scanLineAnimation{ [UIViewbeginAnimations:nilcontext:nil]; [UIViewsetAnimationDuration:4.f]; //设置代理 [UIViewsetAnimationDelegate:self]; //设置动画执行完毕调用的事件 [UIViewsetAnimationDidStopSelector:@selector(didViewAnimation)]; _lineImageView.frame=CGRectMake(leftWith,topHeight+lightHeight-2,lightWidth,2); [UIViewcommitAnimations]; } -(void)didViewAnimation{ //self.navigationController _lineImageView.frame=CGRectMake(leftWith,topHeight,lightWidth,2); [selfscanLineAnimation]; } -(void)insertLayerWithFrame:(CGRect)framewithBackgroundColor:(UIColor*)backgroundColor{ @autoreleasepool{ CALayer*layer=[CALayerlayer]; layer.backgroundColor=backgroundColor.CGColor; layer.frame=frame; [self.view.layeraddSublayer:layer]; } } //初始化layer层,绘制半透明区域 -(void)initLayer{ //公共参数 UIColor*fillColor=[UIColorcolorWithRed:0xae/255.fgreen:0xae/255.fblue:0xae/255.falpha:0.4]; UIColor*crossColor=[UIColorgreenColor]; CGRectscreenRect=[UIScreenmainScreen].bounds; [selfinsertLayerWithFrame:CGRectMake(0,0,leftWith,screenRect.size.height)withBackgroundColor:fillColor]; [selfinsertLayerWithFrame:CGRectMake(leftWith,0,lightWidth,topHeight)withBackgroundColor:fillColor]; [selfinsertLayerWithFrame:CGRectMake(leftWith+lightWidth,0,leftWith,screenRect.size.height)withBackgroundColor:fillColor]; [selfinsertLayerWithFrame:CGRectMake(leftWith,topHeight+lightHeight,lightWidth,topHeight)withBackgroundColor:fillColor]; [selfinsertLayerWithFrame:CGRectMake(leftWith,topHeight,crossLineWidth,crossLineHeight)withBackgroundColor:crossColor]; [selfinsertLayerWithFrame:CGRectMake(leftWith,topHeight,crossLineHeight,crossLineWidth)withBackgroundColor:crossColor]; [selfinsertLayerWithFrame:CGRectMake(leftWith+lightWidth-crossLineHeight,topHeight,crossLineHeight,crossLineWidth)withBackgroundColor:crossColor]; [selfinsertLayerWithFrame:CGRectMake(leftWith+lightWidth-crossLineWidth,topHeight,crossLineWidth,crossLineHeight)withBackgroundColor:crossColor]; [selfinsertLayerWithFrame:CGRectMake(leftWith,topHeight+lightHeight-crossLineHeight,crossLineWidth,crossLineHeight)withBackgroundColor:crossColor]; [selfinsertLayerWithFrame:CGRectMake(leftWith,topHeight+lightHeight-crossLineWidth,crossLineHeight,crossLineWidth)withBackgroundColor:crossColor]; [selfinsertLayerWithFrame:CGRectMake(leftWith+lightWidth-crossLineHeight,topHeight+lightHeight-crossLineWidth,crossLineHeight,crossLineWidth)withBackgroundColor:crossColor]; [selfinsertLayerWithFrame:CGRectMake(leftWith+lightWidth-crossLineWidth,topHeight+lightHeight-crossLineHeight,crossLineWidth,crossLineHeight)withBackgroundColor:crossColor]; } -(void)initScanCode{ @autoreleasepool{ _captureDevice=[AVCaptureDevicedefaultDeviceWithMediaType:AVMediaTypeVideo]; _captureInput=[AVCaptureDeviceInputdeviceInputWithDevice:_captureDeviceerror:nil]; _captureOutput=[[AVCaptureMetadataOutputalloc]init]; [_captureOutputsetMetadataObjectsDelegate:selfqueue:dispatch_get_main_queue()]; if(_isRectScan){ CGRectscreenRect=[UIScreenmainScreen].bounds; [_captureOutputsetRectOfInterest:CGRectMake(topHeight/screenRect.size.height,leftWith/screenRect.size.width,lightHeight/screenRect.size.height,lightWidth/screenRect.size.width)]; } _captureSession=[[AVCaptureSessionalloc]init]; [_captureSessionsetSessionPreset:AVCaptureSessionPresetHigh]; if([_captureSessioncanAddInput:_captureInput]) { [_captureSessionaddInput:_captureInput]; } if([_captureSessioncanAddOutput:_captureOutput]) { [_captureSessionaddOutput:_captureOutput]; } _captureOutput.metadataObjectTypes=@[AVMetadataObjectTypeQRCode]; _capturePreview=[AVCaptureVideoPreviewLayerlayerWithSession:_captureSession]; _capturePreview.videoGravity=AVLayerVideoGravityResizeAspectFill; _capturePreview.frame=self.view.layer.bounds; [self.view.layerinsertSublayer:_capturePreviewatIndex:0]; [_captureSessionstartRunning]; } } -(void)captureOutput:(AVCaptureOutput*)captureOutputdidOutputMetadataObjects:(NSArray*)metadataObjectsfromConnection:(AVCaptureConnection*)connection { if(metadataObjects!=nil&&[metadataObjectscount]>0){ AVMetadataMachineReadableCodeObject*metadataObj=[metadataObjectsobjectAtIndex:0]; NSString*scanCodeResult; if([[metadataObjtype]isEqualToString:AVMetadataObjectTypeQRCode]){ [selfstopScanCode]; scanCodeResult=metadataObj.stringValue; //回调信息 if(_delegate&&[_delegaterespondsToSelector:@selector(scanCodeResultByViewController:withScanCodeResult:)]){ [_delegatescanCodeResultByViewController:selfwithScanCodeResult:scanCodeResult]; [self.navigationControllerpopViewControllerAnimated:YES]; } }else{ NSLog(@"扫描信息错误!"); } } } -(void)systemFlashLight { #if!TARGET_IPHONE_SIMULATOR if([_captureDevicehasTorch]&&[self.captureDevicehasFlash]) { [_captureSessionbeginConfiguration]; [_captureDevicelockForConfiguration:nil]; if(_captureDevice.torchMode==AVCaptureTorchModeOff) { _flashLightBtn.selected=YES; [_captureDevicesetTorchMode:AVCaptureTorchModeOn]; [_captureDevicesetFlashMode:AVCaptureFlashModeOn]; } else{ _flashLightBtn.selected=NO; [_captureDevicesetTorchMode:AVCaptureTorchModeOff]; [_captureDevicesetFlashMode:AVCaptureFlashModeOff]; } [_captureDeviceunlockForConfiguration]; [_captureSessioncommitConfiguration]; } #else [CommonUtilshowAlert:G_ALERTTITLEwithMessage:@"虚拟设备不能运行摄像头!"]; #endif } -(void)stopScanCode{ [_captureSessionstopRunning]; _captureSession=nil; _captureDevice=nil; _captureInput=nil; _captureOutput=nil; [_capturePreviewremoveFromSuperlayer]; } -(void)didReceiveMemoryWarning{ [superdidReceiveMemoryWarning]; } @end
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!