扫描二维码、条形码

2018-08-10  本文已影响0人  Mr_Watson
#import "ScanQRCoreViewController.h"
@import AVFoundation;

#define TOP (kScreenH-220-kNavbarHeight)/2
#define LEFT (kScreenW-220)/2

#define kScanRect CGRectMake(LEFT, TOP, 220, 220)
@interface ScanQRCoreViewController ()<AVCaptureMetadataOutputObjectsDelegate>{
    int num;
    BOOL upOrdown;
}
@property (nonatomic, strong) AVCaptureDevice * device;
@property (nonatomic, strong) AVCaptureDeviceInput * input;
@property (nonatomic, strong) AVCaptureMetadataOutput * output;
@property (nonatomic, strong) AVCaptureSession * session;
@property (nonatomic, strong) AVCaptureVideoPreviewLayer * preview;

@property (nonatomic, strong) NSTimer * timer;
@property (nonatomic, strong) UIImageView * line;
@property (nonatomic, strong) UILabel *descriptionLabel;

@end

@implementation ScanQRCoreViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.title = @"扫一扫";
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self configView];
    
}

-(void)configView{
    
    UIImageView * imageView = [[UIImageView alloc]initWithFrame:kScanRect];
    imageView.image = [UIImage imageNamed:@"scan_border"];
    [self.view addSubview:imageView];
    
    upOrdown = NO;
    num =0;

    _line = [[UIImageView alloc] initWithFrame:CGRectMake(LEFT, TOP+10, 220, 2)];
    _line.image = [UIImage imageNamed:@"scan_line"];
    [self.view addSubview:_line];
    
    _descriptionLabel = [[UILabel alloc] init];
    _descriptionLabel.textColor = [UIColor whiteColor];
    _descriptionLabel.font = [UIFont systemFontOfSize:14];
    _descriptionLabel.textAlignment = NSTextAlignmentCenter;
    _descriptionLabel.text = @"将二维码/条码放入框内,即可自动扫描";
    [self.view addSubview:_descriptionLabel];
    [_descriptionLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(imageView.mas_bottom).offset(18);
        make.centerX.equalTo(self.view);
    }];
    
    _timer = [NSTimer scheduledTimerWithTimeInterval:.02 target:self selector:@selector(animation) userInfo:nil repeats:YES];
    
}

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self setCropRect:kScanRect];//view添加遮罩效果
    
    [self setupCamera];//启动摄像头
}

-(void)animation {//扫描条动画效果
    if (upOrdown == NO) {
        num ++;
        _line.frame = CGRectMake(LEFT, TOP+10+2*num, 220, 2);
        if (2*num == 200) {
            upOrdown = YES;
        }
    }
    else {
        num --;
        _line.frame = CGRectMake(LEFT, TOP+10+2*num, 220, 2);
        if (num == 0) {
            upOrdown = NO;
        }
    }
    
}


- (void)setCropRect:(CGRect)cropRect{
    CAShapeLayer *cropLayer = [[CAShapeLayer alloc] init];
    
    UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:self.view.bounds cornerRadius:0];
    UIBezierPath *rectPath = [UIBezierPath bezierPathWithRect:cropRect];
    [path appendPath:rectPath];
    [cropLayer setFillRule:kCAFillRuleEvenOdd];//生成空心遮罩
    [cropLayer setPath:path.CGPath];
    [cropLayer setFillColor:[UIColor blackColor].CGColor];
    [cropLayer setOpacity:0.3];
    [cropLayer setNeedsDisplay];
    
    [self.view.layer addSublayer:cropLayer];
    
}

- (void)setupCamera {
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    if (device==nil) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"设备没有摄像头" preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }]];
        [self presentViewController:alert animated:YES completion:nil];
        return;
    }
    // 1.Device 获取摄像设备
    _device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
    // 2.Input 创建输入流
    _input = [AVCaptureDeviceInput deviceInputWithDevice:self.device error:nil];
    
    // 3.Output 创建输出流
    _output = [[AVCaptureMetadataOutput alloc]init];
    
    // 4.设置代理 在主线程里刷新
    [_output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    
    // 设置扫描区域
    CGFloat top = TOP/kScreenH;
    CGFloat left = LEFT/kScreenW;
    CGFloat width = 220/kScreenW;
    CGFloat height = 220/kScreenH;
    ///top 与 left 互换  width 与 height 互换
    [_output setRectOfInterest:CGRectMake(top,left, height, width)];
    
    
    // 5.Session 初始化会话对象
    _session = [[AVCaptureSession alloc]init];
    
    // 高质量采集率
    [_session setSessionPreset:AVCaptureSessionPresetHigh];
    
    // 5.1 添加会话输入
    if ([_session canAddInput:self.input]) {
        [_session addInput:self.input];
    }
    
    // 5.2 添加会话输出
    if ([_session canAddOutput:self.output]) {
        [_session addOutput:self.output];
    }
    
    // 6.设置输出数据类型
    // 设置扫码支持的编码格式(如下设置条形码和二维码兼容)
    [_output setMetadataObjectTypes:@[AVMetadataObjectTypeQRCode,
                                     AVMetadataObjectTypeEAN13Code,
                                     AVMetadataObjectTypeEAN8Code,
                                     AVMetadataObjectTypeCode128Code]];
    
    // 7.Preview 实例化预览图层 传递_session是为了告诉图层将来显示什么内容
    _preview =[AVCaptureVideoPreviewLayer layerWithSession:_session];
    _preview.videoGravity = AVLayerVideoGravityResizeAspectFill;
    _preview.frame =self.view.layer.bounds;
    
    // 8.将图层插入当前视图
    [self.view.layer insertSublayer:_preview atIndex:0];
    
    // 9.Start 启动会话
    [_session startRunning];
}

#pragma mark AVCaptureMetadataOutputObjectsDelegate
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
    NSString *stringValue;
    
    if ([metadataObjects count] >0) {
        //停止扫描
        [_session stopRunning];
        [_timer setFireDate:[NSDate distantFuture]];
        
        AVMetadataMachineReadableCodeObject * metadataObject = [metadataObjects objectAtIndex:0];
        stringValue = metadataObject.stringValue;
        NSLog(@"扫描结果:%@",stringValue);
        
        if ([stringValue isEqualToString:@""]) {
            [self.view showMsg:@"无扫描信息"];
            return;
        }
        
        if (_session != nil && _timer != nil) {
            [_session startRunning];
            [_timer setFireDate:[NSDate date]];
        }
        
        //扫描到二维码/条形码信息后返回上一界面并传回扫描结果
        if (self.numBlock) {
            self.numBlock(stringValue);
        }
        [self.navigationController popViewControllerAnimated:YES];

    } else {
        NSLog(@"无扫描信息");
        return;
    }
    
}

@end
ScanQRCore.gif
上一篇下一篇

猜你喜欢

热点阅读