扫描功能小结 (扫描二维码、条形码)

此次扫码功能以iOS系统原生的AVFoundation框架为基础。

废话不多说,直接上代码

#import <UIKit/UIKit.h>

@interface ScanViewController : UIViewController

@end
创建扫描界面

在.m文件中创建对象

#import "ScanViewController.h"
#import <AVFoundation/AVFoundation.h>

#import "UserInputCodeViewController.h"
#import "ScanResultViewController.h"

@interface ScanViewController ()<AVCaptureMetadataOutputObjectsDelegate>

@property (nonatomic, strong) AVCaptureDevice *device;

@property (nonatomic, strong) AVCaptureDeviceInput *input;

@property (nonatomic, strong) AVCaptureMetadataOutput *output;

@property (nonatomic, strong) AVCaptureSession *session;

@property (nonatomic, strong) AVCaptureVideoPreviewLayer *previewLayer;

/*** 专门用于保存描边的图层 ***/
@property (nonatomic,strong) CALayer *containerLayer;
/**
 扫描范围
 */
@property(nonatomic, strong) UIView *scanFrame;
@property(nonatomic, strong) UIView *line;

//@property (nonatomic, strong) UIImageView *scanArea;
@property (nonatomic, strong) UILabel *lightLb;

/**
 是否打开灯光
 */
@property (nonatomic, assign) BOOL isLightOn;

@end

@implementation ScanViewController

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if (!_session ) {
        [self startScan];
    }
    [self refreshScanLineAnimation];
}

-(void)refreshScanLineAnimation {
    if (_line) {
        [self scanLineAnimate];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"扫码开锁";
    self.view.backgroundColor = [UIColor whiteColor];
    
    _isLightOn = NO;
    
    [self initViews];
    
    [self initConner];
    
    [self startScan];
}

-(void)initViews {
    CGRect frame = CGRectZero;
    
    frame.origin.x = (SCREEN_WIDTH - 230) / 2;
    frame.origin.y = (SCREEN_HEIGHT - 500) / 2;
    frame.size.width = 230;
    frame.size.height= 230;
    
    UIView* view = [[UIView alloc] initWithFrame:frame];
    view.backgroundColor= [UIColor clearColor];
    view.layer.borderWidth = 1;
    view.layer.borderColor = [[UIColor grayColor] CGColor];
    self.scanFrame = view;
    [self.view addSubview:view];
    
    //top
    UIView* shadow = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, view.frame.origin.y)];
    shadow.backgroundColor = [UIColor blackColor];
    shadow.alpha = 0.5;
    [self.view addSubview:shadow];
    
    //bottom
    shadow = [[UIView alloc] initWithFrame:CGRectMake(0, view.frame.origin.y + view.frame.size.height, SCREEN_WIDTH, SCREEN_HEIGHT - (view.frame.origin.y + view.frame.size.height))];
    shadow.backgroundColor = [UIColor blackColor];
    shadow.alpha = 0.5;
    [self.view addSubview:shadow];
    
    //left
    shadow = [[UIView alloc] initWithFrame:CGRectMake(0, view.frame.origin.y, (SCREEN_WIDTH - view.frame.size.width) / 2, view.frame.size.height)];
    shadow.backgroundColor = [UIColor blackColor];
    shadow.alpha = 0.5;
    [self.view addSubview:shadow];
    
    //right
    shadow = [[UIView alloc] initWithFrame:CGRectMake(view.frame.origin.x + view.frame.size.width, view.frame.origin.y, (SCREEN_WIDTH - view.frame.size.width) / 2, view.frame.size.height)];
    shadow.backgroundColor = [UIColor blackColor];
    shadow.alpha = 0.5;
    [self.view addSubview:shadow];
    
    _line = [[UIView alloc] initWithFrame:CGRectMake(view.frame.origin.x + 1, view.frame.origin.y + 1, frame.size.width - 2, 3)];
    _line.backgroundColor = UIColorFromRGB(0x28a0f0);
    [self.view addSubview:_line];
    
    UILabel* label = [[UILabel alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(view.frame) + HEIGTHCUSTOME(70), _line.frame.size.width, 15)];
    label.font = UIFontWithPX(26);
    label.textColor = [UIColor whiteColor];
    label.textAlignment = NSTextAlignmentCenter;
    label.center = CGPointMake(_line.center.x, label.center.y);
    label.text = @"请对准充电箱上的二维码";
    [self.view addSubview:label];
    
    //light
    UIButton* light = [UIButton buttonWithType:UIButtonTypeCustom];
    light.frame = CGRectMake(0, view.frame.origin.y + view.frame.size.height + 120, 100, 100);
//    light.center = CGPointMake(view.frame.origin.x + view.frame.size.width - 50, light.center.y);
    light.center = CGPointMake(view.center.x, light.center.y);
    light.backgroundColor = [UIColor clearColor];
    [light setImage:IMAGE(@"flashlight_off") forState:UIControlStateNormal];
    [light addTarget:self action:@selector(openLight:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:light];
    
    _lightLb = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 20)];
    _lightLb.center = CGPointMake(light.center.x, light.center.y + 50);
    _lightLb.text = @"打开手电筒";
    _lightLb.textAlignment = NSTextAlignmentCenter;
    _lightLb.textColor = [UIColor whiteColor];
    _lightLb.font = [UIFont systemFontOfSize:14];
    [self.view addSubview:_lightLb];
}

- (void)initConner {
    CGFloat w = 2;
    CGFloat h = 10;
    CGFloat d = 2;
    CGPoint point = CGPointZero;
    
    //left - top
    point = CGPointMake(_scanFrame.frame.origin.x - w - d, _scanFrame.frame.origin.y - w - d);
    UIView* view = [[UIView alloc] initWithFrame:CGRectMake(point.x, point.y, w, h)];
    view.backgroundColor = UIColorFromRGB(0x28a0f0);
    [self.view addSubview:view];
    
    view = [[UIView alloc] initWithFrame:CGRectMake(point.x, point.y, h, w)];
    view.backgroundColor = UIColorFromRGB(0x28a0f0);
    [self.view addSubview:view];
    
    //left - down
    point = CGPointMake(_scanFrame.frame.origin.x - w - d, _scanFrame.frame.origin.y + _scanFrame.frame.size.height + d + w - h);
    view = [[UIView alloc] initWithFrame:CGRectMake(point.x, point.y, w, h)];
    view.backgroundColor = UIColorFromRGB(0x28a0f0);
    [self.view addSubview:view];
    
    point = CGPointMake(point.x, _scanFrame.frame.origin.y + _scanFrame.frame.size.height + d);
    view = [[UIView alloc] initWithFrame:CGRectMake(point.x, point.y, h, w)];
    view.backgroundColor = UIColorFromRGB(0x28a0f0);
    [self.view addSubview:view];
    
    //right - top
    point = CGPointMake(_scanFrame.frame.origin.x + _scanFrame.frame.size.width + d, _scanFrame.frame.origin.y - w - d);
    view = [[UIView alloc] initWithFrame:CGRectMake(point.x, point.y, w, h)];
    view.backgroundColor = UIColorFromRGB(0x28a0f0);
    [self.view addSubview:view];
    
    point = CGPointMake(_scanFrame.frame.origin.x + _scanFrame.frame.size.width + w + d - h, point.y);
    view = [[UIView alloc] initWithFrame:CGRectMake(point.x, point.y, h, w)];
    view.backgroundColor = UIColorFromRGB(0x28a0f0);
    [self.view addSubview:view];
    
    //right - down
    point = CGPointMake(_scanFrame.frame.origin.x + _scanFrame.frame.size.width + d, _scanFrame.frame.origin.y + _scanFrame.frame.size.height + w + d - h);
    view = [[UIView alloc] initWithFrame:CGRectMake(point.x, point.y, w, h)];
    view.backgroundColor = UIColorFromRGB(0x28a0f0);
    [self.view addSubview:view];
    
    point = CGPointMake(point.x + w - h, _scanFrame.frame.origin.y + _scanFrame.frame.size.height + d);
    view = [[UIView alloc] initWithFrame:CGRectMake(point.x, point.y, h, w)];
    view.backgroundColor = UIColorFromRGB(0x28a0f0);
    [self.view addSubview:view];
}

- (void)scanLineAnimate {
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:2];
    [UIView setAnimationCurve:UIViewAnimationCurveLinear];
    [UIView setAnimationRepeatAutoreverses:YES];
    [UIView setAnimationRepeatCount:HUGE_VALF];
    _line.center = CGPointMake(_line.center.x, _scanFrame.frame.origin.y + _scanFrame.frame.size.height - 5);
    [UIView commitAnimations];
}

- (void)openLight:(UIButton*)sender {
    [_device lockForConfiguration:nil];
    if (!sender.selected) {
        [sender setImage:IMAGE(@"flashlight_on") forState:UIControlStateNormal];
        [_device setTorchMode:AVCaptureTorchModeOn];
        [_device setFlashMode:AVCaptureFlashModeOn];
        _lightLb.text = @"关闭手电筒";
        sender.selected = YES;
    } else {
        [sender setImage:IMAGE(@"flashlight_off") forState:UIControlStateNormal];
        [_device setTorchMode:AVCaptureTorchModeOff];
        [_device setFlashMode:AVCaptureFlashModeOff];
        _lightLb.text = @"打开手电筒";
        sender.selected = NO;
    }
    [_device unlockForConfiguration];
}

- (void)startScan {
    if (![self.session canAddInput:self.input]) return;
    [self.session addInput:self.input];
    
    if (![self.session canAddOutput:self.output]) return;
    [self.session addOutput:self.output];
    
//    self.output.metadataObjectTypes = self.output.availableMetadataObjectTypes;     // 如此设置,可扫描二维码、条形码
    [self.output setMetadataObjectTypes:@[AVMetadataObjectTypeQRCode]];
    
    [self.output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    
    [self.view.layer insertSublayer:self.previewLayer atIndex:0];
    
    [self.view.layer addSublayer:self.containerLayer];
   
    [self.session startRunning];
}

- (void)drawLine:(AVMetadataMachineReadableCodeObject *)objc {
    NSArray *array = objc.corners;
    
    CAShapeLayer *layer = [[CAShapeLayer alloc] init];
    layer.lineWidth = 2;
    layer.strokeColor = [UIColor greenColor].CGColor;
    layer.fillColor = [UIColor clearColor].CGColor;
    
    UIBezierPath *path = [[UIBezierPath alloc] init];
    CGPoint point = CGPointZero;
    int index = 0;
    
    CFDictionaryRef dict = (__bridge CFDictionaryRef)(array[index++]);
    CGPointMakeWithDictionaryRepresentation(dict, &point);
    
    [path moveToPoint:point];
    
    for (int i = 1; i<array.count; i++) {
        CGPointMakeWithDictionaryRepresentation((__bridge CFDictionaryRef)array[i], &point);
        [path addLineToPoint:point];
    }
    [path closePath];
    layer.path = path.CGPath;
    [self.containerLayer addSublayer:layer];
}

- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection {
    if (_session) {
        [_session stopRunning];
    }
    [_output setMetadataObjectsDelegate:nil queue:dispatch_get_main_queue()];
    
    // id 类型不能点语法,所以要先去取出数组中对象
    id object = [metadataObjects lastObject];
    if ([object isKindOfClass:[AVMetadataMachineReadableCodeObject class]]) {
        NSString *stringValue;
        if ([metadataObjects count] >0) {
            AVMetadataMachineReadableCodeObject * metadataObject = [metadataObjects lastObject];
            stringValue = metadataObject.stringValue;
        }
        
        [self judgeCode:stringValue];
//        [self judgeCode:@"test00001"];
        
        [self clearLayers];
        AVMetadataMachineReadableCodeObject *obj = (AVMetadataMachineReadableCodeObject *)[self.previewLayer transformedMetadataObjectForMetadataObject:object];
        [self drawLine:obj];
    }
}
// 初始化扫描界面
-(void)initPreviewImg {
    [_output setMetadataObjectsDelegate:nil queue:dispatch_get_main_queue()];
    [_session stopRunning];
    [_session removeOutput:_output];
    [_session removeInput:_input];
    
    [_containerLayer removeFromSuperlayer];
    [_previewLayer removeFromSuperlayer];
    
    _containerLayer = nil;       //不置空,二维码的彩色边框无法去除
    _session = nil;                 // 不置空,返回本页面,出现白屏
    _output = nil;
    _previewLayer = nil;        // 不置空,会有空指针,由下个界面返回时会出现崩溃
    /*
     Assertion failed: (_inputInternal->figCaptureSession == NULL), function __44-[AVCaptureInput attachToFigCaptureSession:]_block_invoke, file /BuildRoot/Library/Caches/com.apple.xbs/Sources/EmbeddedAVFoundation/EmbeddedAVFoundation-1184.7/Aspen/AVCaptureInput.m, line 132.
     */
}

- (void)clearLayers {
    if (self.containerLayer.sublayers) {
        for (CALayer *subLayer in self.containerLayer.sublayers) {
            [subLayer removeFromSuperlayer];
        }
    }
}
#pragma mark -------- 懒加载---------
- (AVCaptureDevice *)device {
    if (_device == nil) {
        _device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    }
    return _device;
}

- (AVCaptureDeviceInput *)input {
    if (_input == nil) {
        _input = [AVCaptureDeviceInput deviceInputWithDevice:self.device error:nil];
    }
    return _input;
}

- (AVCaptureSession *)session {
    if (_session == nil) {
        _session = [[AVCaptureSession alloc] init];
    }
    return _session;
}

- (AVCaptureVideoPreviewLayer *)previewLayer {
    if (_previewLayer == nil) {
        _previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:self.session];
        _previewLayer.frame = self.view.bounds;
    }
    return _previewLayer;
}

- (AVCaptureMetadataOutput *)output {
    if (_output == nil) {
        _output = [[AVCaptureMetadataOutput alloc] init];
        CGRect viewRect = self.view.frame;
        CGRect containerRect = _scanFrame.frame;
        CGFloat x = containerRect.origin.y / viewRect.size.height;
        CGFloat y = containerRect.origin.x / viewRect.size.width;
        CGFloat width = containerRect.size.height / viewRect.size.height;
        CGFloat height = containerRect.size.width / viewRect.size.width;
        _output.rectOfInterest = CGRectMake(x, y, width, height);
    }
    return _output;
}

- (CALayer *)containerLayer {
    if (_containerLayer == nil) {
        _containerLayer = [[CALayer alloc] init];
        _containerLayer.frame = self.view.bounds;
    }
    return _containerLayer;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
创建对象

 

转载于:https://www.cnblogs.com/linzhengbo/p/6831159.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
基于C++&OPENCV 的全景图像拼接 C++是一种广泛使用的编程语言,它是由Bjarne Stroustrup于1979年在新泽西州美利山贝尔实验室开始设计开发的。C++是C语言的扩展,旨在提供更强大的编程能力,包括面向对象编程和泛型编程的支持。C++支持数据封装、继承和多态等面向对象编程的特性和泛型编程的模板,以及丰富的标准库,提供了大量的数据结构和算法,极大地提高了开发效率。12 C++是一种静态类型的、编译式的、通用的、大小写敏感的编程语言,它综合了高级语言和低级语言的特点。C++的语法与C语言非常相似,但增加了许多面向对象编程的特性,如类、对象、封装、继承和多态等。这使得C++既保持了C语言的低级特性,如直接访问硬件的能力,又提供了高级语言的特性,如数据封装和代码重用。13 C++的应用领域非常广泛,包括但不限于教育、系统开发、游戏开发、嵌入式系统、工业和商业应用、科研和高性能计算等领域。在教育领域,C++因其结构化和面向对象的特性,常被选为计算机科学和工程专业的入门编程语言。在系统开发领域,C++因其高效性和灵活性,经常被作为开发语言。游戏开发领域中,C++由于其高效性和广泛应用,在开发高性能游戏和游戏引擎中扮演着重要角色。在嵌入式系统领域,C++的高效和灵活性使其成为理想选择。此外,C++还广泛应用于桌面应用、Web浏览器、操作系统、编译器、媒体应用程序、数据库引擎、医疗工程和机器人等领域。16 学习C++的关键是理解其核心概念和编程风格,而不是过于深入技术细节。C++支持多种编程风格,每种风格都能有效地保证运行时间效率和空间效率。因此,无论是初学者还是经验丰富的程序员,都可以通过C++来设计和实现新系统或维护旧系统。3

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值