废话不多说,直接上代码

**先声明几个类**
@interface QRCodeController ()<AVCaptureMetadataOutputObjectsDelegate>@property(nonatomic,strong)AVCaptureDeviceInput *input;
@property(nonatomic,strong)AVCaptureMetadataOutput *output;
@property(nonatomic,strong)AVCaptureSession *session;
@property(nonatomic,strong)AVCaptureVideoPreviewLayer *prelayer;
@end- (void)instanceDevice{line_tag = 1872637;//获取摄像设备AVCaptureDevice * device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];//创建输入流AVCaptureDeviceInput * input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];//创建输出流AVCaptureMetadataOutput * output = [[AVCaptureMetadataOutput alloc]init];//设置扫描区域,很简单被很多人忽略的属性,注意这是是按比例计算的!!!CGSize size = self.view.bounds.size;CGRect cropRect = CGRectMake(40, 180, 240, 240);output.rectOfInterest = CGRectMake(cropRect.origin.y/size.height,cropRect.origin.x/size.width,cropRect.size.height/size.height,cropRect.size.width/size.width);//设置代理 在主线程里刷新[output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];//初始化链接对象self.session = [[AVCaptureSession alloc]init];//高质量采集率[self.session setSessionPreset:AVCaptureSessionPresetHigh];if (input) {[self.session addInput:input];}if (output) {[self.session addOutput:output];//设置扫码支持的编码格式(如下设置条形码和二维码兼容)NSMutableArray *a = [[NSMutableArray alloc] init];if ([output.availableMetadataObjectTypes containsObject:AVMetadataObjectTypeQRCode]) {[a addObject:AVMetadataObjectTypeQRCode];}if ([output.availableMetadataObjectTypes containsObject:AVMetadataObjectTypeEAN13Code]) {[a addObject:AVMetadataObjectTypeEAN13Code];}if ([output.availableMetadataObjectTypes containsObject:AVMetadataObjectTypeEAN8Code]) {[a addObject:AVMetadataObjectTypeEAN8Code];}if ([output.availableMetadataObjectTypes containsObject:AVMetadataObjectTypeCode128Code]) {[a addObject:AVMetadataObjectTypeCode128Code];}output.metadataObjectTypes=a;}//创建特殊的现实layerAVCaptureVideoPreviewLayer * layer = [AVCaptureVideoPreviewLayer layerWithSession:self.session];self.prelayer = layer;layer.videoGravity=AVLayerVideoGravityResizeAspectFill;layer.frame=self.view.layer.bounds;[self.view.layer insertSublayer:layer atIndex:0];//调用创建扫码页面方法[self setOverlayPickerView];//给session添加一个观察者[self.session addObserver:self forKeyPath:@"running" options:NSKeyValueObservingOptionNew context:nil];//开始捕获[self.session startRunning];
}

监听扫码状态-修改扫描动画

- (void)observeValueForKeyPath:(NSString *)keyPathofObject:(id)objectchange:(NSDictionary *)changecontext:(void *)context{if ([object isKindOfClass:[AVCaptureSession class]]) {BOOL isRunning = ((AVCaptureSession *)object).isRunning;if (isRunning) {[self addAnimation];}else{[self removeAnimation];}}
}

* 获取扫码结果*

-(void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection{if (metadataObjects.count>0) {[self.session stopRunning];AVMetadataMachineReadableCodeObject * metadataObject = [metadataObjects objectAtIndex :0];//输出扫描字符串NSString *data = metadataObject.stringValue;
//创建第一个提示窗窗口UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:data preferredStyle:(UIAlertControllerStyleAlert)];UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction *action) {//我自己加的方法,点击"好"后,将推出的模态窗口推出[self selfRemoveFromSuperview];}];[alertController addAction:okAction];[self presentViewController:alertController animated:YES completion:nil];}
}

创建扫码界面,为了简单我没有设置自动布局,就按6S手机适配的

- (void)setOverlayPickerView
{//左侧的viewUIImageView *leftView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 30, ScreenHeight)];
//    UIImageView *leftView = [[UIImageView alloc] init];leftView.alpha = 0.5;leftView.backgroundColor = [UIColor blackColor];[self.view addSubview:leftView];
//    [leftView mas_makeConstraints:^(MASConstraintMaker *make) {//        make.left.equalTo(self.view.mas_left);
//        make.top.equalTo(self.view.mas_top);
//        make.width.mas_equalTo(100);
//        make.height.mas_equalTo(ScreenHeight);
//    }];//右侧的viewUIImageView *rightView = [[UIImageView alloc] initWithFrame:CGRectMake(ScreenWidth-30, 0, 30, ScreenHeight)];rightView.alpha = 0.5;rightView.backgroundColor = [UIColor blackColor];[self.view addSubview:rightView];//最上部viewUIImageView* upView = [[UIImageView alloc] initWithFrame:CGRectMake(30, 0, ScreenWidth-60, (self.view.center.y-(ScreenWidth-60)/2))];upView.alpha = 0.5;upView.backgroundColor = [UIColor blackColor];[self.view addSubview:upView];//底部viewUIImageView * downView = [[UIImageView alloc] initWithFrame:CGRectMake(30, (self.view.center.y+(ScreenWidth-60)/2), (ScreenWidth-60), (ScreenHeight-(self.view.center.y-(ScreenWidth-60)/2)))];downView.alpha = 0.5;downView.backgroundColor = [UIColor blackColor];[self.view addSubview:downView];UIImageView *centerView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth-60, ScreenWidth-60)];centerView.center = self.view.center;centerView.image = [UIImage imageNamed:@"扫描框.png"];centerView.contentMode = UIViewContentModeScaleAspectFit;centerView.backgroundColor = [UIColor clearColor];[self.view addSubview:centerView];UIImageView *line = [[UIImageView alloc] initWithFrame:CGRectMake(30, CGRectGetMaxY(upView.frame), ScreenWidth-60, 2)];line.tag = line_tag;line.image = [UIImage imageNamed:@"扫描线.png"];line.contentMode = UIViewContentModeScaleAspectFill;line.backgroundColor = [UIColor clearColor];[self.view addSubview:line];UILabel *msg = [[UILabel alloc] initWithFrame:CGRectMake(30, CGRectGetMinY(downView.frame), ScreenWidth-60, 60)];msg.backgroundColor = [UIColor clearColor];msg.textColor = [UIColor whiteColor];msg.textAlignment = NSTextAlignmentCenter;msg.font = [UIFont systemFontOfSize:16];msg.text = @"将二维码放入框内,即可自动扫描";[self.view addSubview:msg];UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, ScreenHeight-100, ScreenWidth, 100)];label.backgroundColor = [UIColor clearColor];label.textColor = [UIColor whiteColor];label.textAlignment = NSTextAlignmentCenter;label.font = [UIFont systemFontOfSize:24];label.text = @"世界那么大,我想去扫扫";[self.view addSubview:label];CGRect leftFrame;leftFrame = CGRectMake(0, 10, 60, 64);UIButton *leftButton= [UIButton buttonWithType:UIButtonTypeCustom];leftButton.frame =leftFrame;[leftButton addTarget:self action:@selector(dismissOverlayView:) forControlEvents:UIControlEventTouchUpInside];[leftButton setImage:[UIImage imageNamed:@"白色返回_想去"] forState:UIControlStateNormal];[self.view addSubview:leftButton];
}

添加扫码动画

- (void)addAnimation{UIView *line = [self.view viewWithTag:line_tag];line.hidden = NO;CABasicAnimation *animation = [QRCodeController moveYTime:2 fromY:[NSNumber numberWithFloat:0] toY:[NSNumber numberWithFloat:ScreenWidth-60-2] rep:OPEN_MAX];[line.layer addAnimation:animation forKey:@"LineAnimation"];
}+ (CABasicAnimation *)moveYTime:(float)time fromY:(NSNumber *)fromY toY:(NSNumber *)toY rep:(int)rep
{CABasicAnimation *animationMove = [CABasicAnimation animationWithKeyPath:@"transform.translation.y"];[animationMove setFromValue:fromY];[animationMove setToValue:toY];animationMove.duration = time;animationMove.delegate = self;animationMove.repeatCount  = rep;animationMove.fillMode = kCAFillModeForwards;animationMove.removedOnCompletion = NO;animationMove.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];return animationMove;
}

去除扫码动画

- (void)removeAnimation{UIView *line = [self.view viewWithTag:line_tag];[line.layer removeAnimationForKey:@"LineAnimation"];line.hidden = YES;
}

将推出的模态控制器移除

- (void)selfRemoveFromSuperview{[self.prelayer removeFromSuperlayer];[self dismissViewControllerAnimated:YES completion:nil];
}//修改状态栏样式
- (UIStatusBarStyle)preferredStatusBarStyle{return UIStatusBarStyleLightContent;
}

iOS 原生二维码扫描(可限制扫描区域)相关推荐

  1. iOS原生二维码扫描(一)

    首先搭建一个最初步的能识别出二维码信息的最基本框架: @interface ScanCodeViewController ()<AVCaptureMetadataOutputObjectsDel ...

  2. iOS 原生二维码扫描和生成

    代码地址如下: http://www.demodashi.com/demo/12551.html 一.效果预览: 功能描述:WSLNativeScanTool是在利用原生API的条件下封装的二维码扫描 ...

  3. IOS 原生二维码、条形码扫描for IOS7 (八)

    转自:http://blog.csdn.net/baidu_31071595/article/details/50878410 同类型文章:http://www.2cto.com/kf/201603/ ...

  4. iOS原生二维码扫码实现(含蒙版和扫码动画)

    #一.iOS实现原生扫码的意义 二维码扫码功能对于现在的iOS App开发来说是非常重要的. 通常为了节省开发时间,很多开发者会采用ZXing和ZBar等第三方SDK进行开发. 这样的好处是快速便捷, ...

  5. iOS 花式二维码生成和二维码识别

    iOS 原生的二维码识别非常之棒,反正比 ZXing 和 ZBar 效果都好些,所以以后打算尽量用原生的二维码识别,然后最近把原生的二维码生成也顺便做了一遍,并且在原有基础上加了一些样式参数,封了一个 ...

  6. iOS 7原生二维码扫描中文gbk编码乱码的解决

    有的二维码生成的含有中文的数据编码是GBK编码,如百度二维码生成器,使用系统原生二维码扫描就会出现乱码,于是开始网上查阅,该试的方法都尝试过了,终于功夫不负有心人,问题得到了解决,先上代码 NSStr ...

  7. iOS开发-二维码扫描和应用跳转

    iOS开发-二维码扫描和应用跳转   序言 前面我们已经调到过怎么制作二维码,在我们能够生成二维码之后,如何对二维码进行扫描呢? 在iOS7之前,大部分应用中使用的二维码扫描是第三方的扫描框架,例如Z ...

  8. iOS--AVFoundation原生二维码与一维码扫描

    概述 实现二维码和条形码扫描,两大开源组件ZBar与ZXing ZBar: 扫描灵敏性,内存较优,但"圆角二维码"扫描比较困难. ZXing: Google Code上的一个开源的 ...

  9. 苹果原生二维码生成与扫描及生成的二维码不清楚的解决方案

    苹果原生二维码生成与扫描及生成的二维码不清楚的解决方案 参考文章: (1)苹果原生二维码生成与扫描及生成的二维码不清楚的解决方案 (2)https://www.cnblogs.com/CoderEYL ...

最新文章

  1. mysql grou平by_MySQL group by对单字分组序和多字段分组的方法讲解
  2. Keras 实现 LSTM
  3. mac 当前文件夹打开终端_Mac上的这些实用你技巧,你知道几个?
  4. EJS学习(五)之EJS的CommonJs规范版本
  5. boost::python::enum_相关的测试程序
  6. 树形动态规划 - 树中距离之和
  7. 使用QT创建PythonGUI程序
  8. 教资科一科二知识点 0312
  9. txt文件循环插入固定字符_第02章 文件和用户管理(2)
  10. 《软件调试》第二版正式发售,看雪给你早鸟价
  11. 台式计算机可以连接蓝牙吗,台式电脑可以连接蓝牙音响吗
  12. html闹钟设置,闹钟的设置.html
  13. 计算机中人民币数字格式,数字转人民币金额大写
  14. 小程序中图片的移动、旋转和缩放功能
  15. 前后端分离详解(转发)
  16. 基于网页在线图书小说电子书阅读系统 毕业设计毕设源码毕业论文开题报告参考(2)网站和用户功能
  17. Python每日一练——第1天:水仙花数
  18. 说明关系型数据库通过索引提升查询效率的背后原理
  19. Windows10设置任务栏透明化
  20. 怎么看越努力,越幸运?

热门文章

  1. 毕业设计-基于BP神经网络的水果识别系统-matlab
  2. Redis的介绍和使用(NoSQL、Jedis)
  3. 详细 解释findIndex和indexOf 区别 以及find
  4. VB.NET对图片读取操作
  5. 向安卓模拟器中添加图片并显示
  6. 程序员颈椎病康复指南(最新)
  7. 用华为手机将录音转文字竟如此简单,手机秒变会议神器,太好用了
  8. 慢速,混合和快速衰减模式。为什么我们要把事情复杂化?
  9. 已知二叉树前序遍历是ADCEFGHB,中序遍历是CDFEGHAB,要求画出二叉树的结构或写出后序遍历
  10. 「论文写作」如何写好论文【摘要】章节