iOS二维码生成及扫码

概要
        现在越来越多的应用加入二维码相关的业务,在iOS开发市场上很多开发人员都在使用第三方的扫码与生成二维码的控件,个人认为此类的第三方控件识别度不高。最近正好整理新框架的事情,研究了一下。具体代码如下
 生成二维码代码
[objc]  view plain  copy
  1. /** 
  2.  *  @author 半    饱, 15-12-18 
  3.  * 
  4.  *  @brief  生成二维码图片 
  5.  * 
  6.  *  @param code   生成二维码图片内容 
  7.  *  @param width  二维码图片宽度 
  8.  *  @param height 二维码图片高度 
  9.  * 
  10.  *  @return 返回UIImage对象 
  11.  */  
  12. - (UIImage *)generateQRCode:(NSString *)code width:(CGFloat)width height:(CGFloat)height {  
  13.     CIImage *qrcodeImage;  
  14.     NSData *data = [code dataUsingEncoding:NSISOLatin1StringEncoding allowLossyConversion:false];  
  15.     CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];  
  16.       
  17.     [filter setValue:data forKey:@"inputMessage"];  
  18.     [filter setValue:@"H" forKey:@"inputCorrectionLevel"];  
  19.     qrcodeImage = [filter outputImage];  
  20.       
  21.     CGFloat scaleX = width / qrcodeImage.extent.size.width;  
  22.     CGFloat scaleY = height / qrcodeImage.extent.size.height;  
  23.     CIImage *transformedImage = [qrcodeImage imageByApplyingTransform:CGAffineTransformScale(CGAffineTransformIdentity, scaleX, scaleY)];  
  24.       
  25.     return [UIImage imageWithCIImage:transformedImage];  
  26. }  

 扫描二维码代码
[objc]  view plain  copy
  1. #import <AVFoundation/AVFoundation.h>  
  2.   
  3. static const float lightWidth = 240.f;  
  4. static const float lightHeight = 240.f;  
  5. static const float crossLineWidth = 2.f;  
  6. static const float crossLineHeight = 15.f;  
  7.   
  8. @interface BBScanCodeViewController ()<AVCaptureMetadataOutputObjectsDelegate> {  
  9.     float leftWith;  
  10.     float topHeight;  
  11. }  
  12. @property (strong , nonatomic ) AVCaptureDevice *captureDevice;  
  13. @property (strong , nonatomic ) AVCaptureDeviceInput *captureInput;  
  14. @property (strong , nonatomic ) AVCaptureMetadataOutput *captureOutput;  
  15. @property (strong , nonatomic ) AVCaptureSession *captureSession;  
  16. @property (strong , nonatomic ) AVCaptureVideoPreviewLayer *capturePreview;  
  17.   
  18. @property (strong,nonatomicUIButton *flashLightBtn;  
  19. @property (strong,nonatomicUIImageView *lineImageView;  
  20.   
  21. @end  
  22.   
  23. @implementation BBScanCodeViewController  
  24. @synthesize captureDevice = _captureDevice;  
  25. @synthesize captureInput = _captureInput;  
  26. @synthesize captureOutput = _captureOutput;  
  27. @synthesize capturePreview = _capturePreview;  
  28. @synthesize captureSession = _captureSession;  
  29. @synthesize  delegate = _delegate;  
  30. @synthesize  isRectScan = _isRectScan;  
  31. @synthesize lineImageView = _lineImageView;  
  32. @synthesize  flashLightBtn = _flashLightBtn;  
  33. - (void)viewDidLoad {  
  34.       
  35.     [super viewDidLoad];  
  36.     self.isShowNavigationItem = YES;  
  37.     CGRect screenRect = [UIScreen mainScreen].bounds;  
  38.     leftWith = (screenRect.size.width - lightWidth) /  2;  
  39.     topHeight =(screenRect.size.height - lightHeight) /  2;  
  40.       
  41. #if !TARGET_IPHONE_SIMULATOR  
  42.     [self initScanCode];  
  43. #endif  
  44.     [self initLayer];  
  45.     [self initViewControl];  
  46.       
  47.       
  48.   
  49.     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(willResignActiveNotification) name:UIApplicationWillResignActiveNotification object:nil]; //监听是否触发home键挂起程序.  
  50.    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didBecomeActiveNotification) name:UIApplicationDidBecomeActiveNotification object:nil]; //监听是否重新进入程序程序.  
  51. }  
  52.   
  53. -(void)viewWillDisappear:(BOOL)animated {  
  54.      [self stopScanCode];  
  55.     [super viewWillDisappear:animated];  
  56. }  
  57.   
  58. - (void)willResignActiveNotification {  
  59.     _flashLightBtn.selected = NO;  
  60. }  
  61. - (void)didBecomeActiveNotification {  
  62.   
  63. }  
  64. //加载界面上的控件,如:加上闪光灯按钮等  
  65. - (void)initViewControl {  
  66.   
  67.     @autoreleasepool {  
  68.         _flashLightBtn = [UIButton buttonWithType:UIButtonTypeCustom];  
  69.         [_flashLightBtn setImage:[UIImage imageNamed:@"OpenFlashLight.png"] forState:UIControlStateNormal];  
  70.         [_flashLightBtn setImage:[UIImage imageNamed:@"CloseFlashLight.png"] forState:UIControlStateSelected];  
  71.         _flashLightBtn.frame = CGRectMake(leftWith, 80.f30.f30.f);  
  72.         [_flashLightBtn addTarget:self action:@selector(systemFlashLight) forControlEvents:UIControlEventTouchUpInside];  
  73.         [self.view addSubview:_flashLightBtn];  
  74.           
  75.         _lineImageView = [[UIImageView alloc] initWithImage:nil];  
  76.         _lineImageView.backgroundColor = [UIColor greenColor];  
  77.         _lineImageView.frame = CGRectMake(leftWith, topHeight, lightWidth, 2);  
  78.         [self.view addSubview:_lineImageView];  
  79.         [self scanLineAnimation];  
  80.     }  
  81.       
  82. }  
  83.   
  84. - (void)scanLineAnimation {  
  85.     [UIView beginAnimations:nil context:nil];  
  86.     [UIView setAnimationDuration:4.f];  
  87.     //设置代理  
  88.     [UIView setAnimationDelegate:self];  
  89.     //设置动画执行完毕调用的事件  
  90.     [UIView setAnimationDidStopSelector:@selector(didViewAnimation)];  
  91.     _lineImageView.frame = CGRectMake(leftWith,topHeight + lightHeight-2,lightWidth,2);  
  92.     [UIView commitAnimations];  
  93.   
  94. }  
  95.   
  96. -(void)didViewAnimation {  
  97. //    self.navigationController  
  98.     _lineImageView.frame = CGRectMake(leftWith, topHeight, lightWidth, 2);  
  99.     [self scanLineAnimation];  
  100. }  
  101.   
  102. - (void)insertLayerWithFrame:(CGRect)frame withBackgroundColor:(UIColor *)backgroundColor {  
  103.     @autoreleasepool {  
  104.         CALayer *layer = [CALayer layer];  
  105.         layer.backgroundColor = backgroundColor.CGColor;  
  106.         layer.frame = frame;  
  107.         [self.view.layer addSublayer:layer];  
  108.     }  
  109. }  
  110. //初始化layer层,绘制半透明区域  
  111. -(void) initLayer {  
  112.     //公共参数  
  113.     UIColor *fillColor = [UIColor colorWithRed:0xae/255.f green:0xae/255.f blue:0xae/255.f alpha:0.4];  
  114.     UIColor *crossColor = [UIColor greenColor];  
  115.     CGRect screenRect = [UIScreen mainScreen].bounds;  
  116.     [self insertLayerWithFrame:CGRectMake(00, leftWith, screenRect.size.height) withBackgroundColor:fillColor];  
  117.     [self insertLayerWithFrame:CGRectMake(leftWith, 0, lightWidth, topHeight) withBackgroundColor:fillColor];  
  118.     [self insertLayerWithFrame:CGRectMake(leftWith + lightWidth, 0, leftWith, screenRect.size.height) withBackgroundColor:fillColor];  
  119.     [self insertLayerWithFrame:CGRectMake(leftWith, topHeight + lightHeight, lightWidth, topHeight) withBackgroundColor:fillColor];  
  120.       
  121.       
  122.     [self insertLayerWithFrame:CGRectMake(leftWith, topHeight, crossLineWidth, crossLineHeight) withBackgroundColor:crossColor];  
  123.     [self insertLayerWithFrame:CGRectMake(leftWith, topHeight, crossLineHeight, crossLineWidth) withBackgroundColor:crossColor];  
  124.       
  125.     [self insertLayerWithFrame:CGRectMake(leftWith + lightWidth - crossLineHeight, topHeight, crossLineHeight, crossLineWidth) withBackgroundColor:crossColor];  
  126.     [self insertLayerWithFrame:CGRectMake(leftWith + lightWidth - crossLineWidth, topHeight, crossLineWidth, crossLineHeight) withBackgroundColor:crossColor];  
  127.       
  128.     [self insertLayerWithFrame:CGRectMake(leftWith, topHeight + lightHeight - crossLineHeight, crossLineWidth, crossLineHeight) withBackgroundColor:crossColor];  
  129.     [self insertLayerWithFrame:CGRectMake(leftWith, topHeight + lightHeight - crossLineWidth, crossLineHeight, crossLineWidth) withBackgroundColor:crossColor];  
  130.       
  131.     [self insertLayerWithFrame:CGRectMake(leftWith + lightWidth - crossLineHeight, topHeight + lightHeight - crossLineWidth, crossLineHeight, crossLineWidth) withBackgroundColor:crossColor];  
  132.     [self insertLayerWithFrame:CGRectMake(leftWith + lightWidth - crossLineWidth, topHeight + lightHeight - crossLineHeight, crossLineWidth, crossLineHeight) withBackgroundColor:crossColor];  
  133. }  
  134.   
  135. -(void)initScanCode {  
  136.     @autoreleasepool {  
  137.         _captureDevice = [ AVCaptureDevice defaultDeviceWithMediaType : AVMediaTypeVideo];  
  138.         _captureInput = [ AVCaptureDeviceInput deviceInputWithDevice : _captureDevice error : nil ];  
  139.         _captureOutput = [[ AVCaptureMetadataOutput alloc ] init ];  
  140.         [_captureOutput setMetadataObjectsDelegate : self queue : dispatch_get_main_queue ()];  
  141.         if (_isRectScan) {  
  142.             CGRect screenRect = [UIScreen mainScreen].bounds;  
  143.             [ _captureOutput setRectOfInterest : CGRectMake (topHeight / screenRect.size.height, leftWith / screenRect.size.width, lightHeight/screenRect.size.height, lightWidth / screenRect.size.width)];  
  144.         }  
  145.   
  146.         _captureSession = [[ AVCaptureSession alloc ] init ];  
  147.         [_captureSession setSessionPreset : AVCaptureSessionPresetHigh ];  
  148.         if ([_captureSession canAddInput : _captureInput ])  
  149.         {  
  150.             [_captureSession addInput : _captureInput ];  
  151.         }  
  152.         if ([_captureSession canAddOutput : _captureOutput ])  
  153.         {  
  154.             [_captureSession addOutput : _captureOutput ];  
  155.         }  
  156.         _captureOutput.metadataObjectTypes = @[AVMetadataObjectTypeQRCode ] ;  
  157.           
  158.         _capturePreview =[ AVCaptureVideoPreviewLayer layerWithSession :_captureSession ];  
  159.         _capturePreview.videoGravity = AVLayerVideoGravityResizeAspectFill ;  
  160.         _capturePreview.frame = self.view.layer.bounds ;  
  161.         [self.view.layer insertSublayer : _capturePreview atIndex : 0 ];  
  162.         [_captureSession startRunning ];  
  163.     }  
  164. }  
  165.   
  166. - ( void )captureOutput:( AVCaptureOutput *)captureOutput didOutputMetadataObjects:( NSArray *)metadataObjects fromConnection:( AVCaptureConnection *)connection  
  167. {  
  168.     if (metadataObjects != nil && [metadataObjects count] > 0) {  
  169.         AVMetadataMachineReadableCodeObject *metadataObj = [metadataObjects objectAtIndex:0];  
  170.         NSString *scanCodeResult;  
  171.         if ([[metadataObj type] isEqualToString:AVMetadataObjectTypeQRCode]) {  
  172.             [self stopScanCode];  
  173.             scanCodeResult = metadataObj.stringValue;  
  174.             //回调信息  
  175.             if (_delegate && [_delegate respondsToSelector:@selector(scanCodeResultByViewController:withScanCodeResult:)]) {  
  176.                 [_delegate scanCodeResultByViewController:self withScanCodeResult:scanCodeResult];  
  177.                 [self.navigationController popViewControllerAnimated:YES];  
  178.             }  
  179.         } else {  
  180.             NSLog(@"扫描信息错误!");  
  181.         }  
  182.     }  
  183. }  
  184.   
  185. - (void)systemFlashLight  
  186. {  
  187. #if !TARGET_IPHONE_SIMULATOR  
  188.     if([_captureDevice hasTorch] && [self.captureDevice hasFlash])  
  189.     {  
  190.         [_captureSession beginConfiguration];  
  191.         [_captureDevice lockForConfiguration:nil];  
  192.         if(_captureDevice.torchMode == AVCaptureTorchModeOff)  
  193.         {  
  194.             _flashLightBtn.selected = YES;  
  195.             [_captureDevice setTorchMode:AVCaptureTorchModeOn];  
  196.             [_captureDevice setFlashMode:AVCaptureFlashModeOn];  
  197.         }  
  198.         else {  
  199.             _flashLightBtn.selected = NO;  
  200.             [_captureDevice setTorchMode:AVCaptureTorchModeOff];  
  201.             [_captureDevice setFlashMode:AVCaptureFlashModeOff];  
  202.         }  
  203.         [_captureDevice unlockForConfiguration];  
  204.         [_captureSession commitConfiguration];  
  205.     }  
  206. #else  
  207.     [CommonUtil showAlert:G_ALERTTITLE withMessage:@"虚拟设备不能运行摄像头!"];  
  208. #endif  
  209. }  
  210.   
  211. -(void)stopScanCode {  
  212.     [_captureSession stopRunning];  
  213.     _captureSession = nil;  
  214.     _captureDevice = nil;  
  215.     _captureInput = nil;  
  216.     _captureOutput = nil;  
  217.     [_capturePreview removeFromSuperlayer];  
  218. }  
  219.   
  220. - (void)didReceiveMemoryWarning {  
  221.     [super didReceiveMemoryWarning];  
  222. }  
  223.   
  224. @end  


版权所有:半 饱 开发专栏
版本转载:http://blog.csdn.net/banbaodevelop
ps:如有转载请加以上信息

你可能感兴趣的:(iOS二维码生成及扫码)