美文网首页iOS开发
iOS开发之二维码扫描

iOS开发之二维码扫描

作者: chasitu | 来源:发表于2019-06-03 18:02 被阅读18次

这段时间用到了二维码扫描,用一个UIView自定义封装了一个二维码扫描控件,内部实现了中部矩形框内扫描,调用也比较简单block回调的形式,不多说了,直接上代码

二维码扫描

SHCustomQRCodeView.h

#import <UIKit/UIKit.h>

typedef void(^BackQRCodeURL)(NSString  *stringValue);

@interface SHCustomQRCodeView : UIView

/**扫描回调*/
@property (nonatomic,copy) BackQRCodeURL backQRCodeURL;

@end

SHCustomQRCodeView.m

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

//颜色(默认支付宝蓝)
#define STYLECOLOR [UIColor colorWithRed:57/255.f green:187/255.f blue:255/255.f alpha:1.0]

@interface SHCustomQRCodeView()<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 ) UIView                  *   hudView;
@end

@implementation SHCustomQRCodeView

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = UIColor.grayColor;
        AVAuthorizationStatus authorizationStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
        BOOL isAvailableA = authorizationStatus == AVAuthorizationStatusRestricted || authorizationStatus == AVAuthorizationStatusDenied;
        if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera] && isAvailableA == NO){//判断相机
            _device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
            _input = [AVCaptureDeviceInput deviceInputWithDevice:_device error:nil];
            _output = [[AVCaptureMetadataOutput alloc] init];
            [_output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
            [_output setRectOfInterest:CGRectMake((frame.size.height - 220)*0.5/UIScreen.mainScreen.bounds.size.height,
                                                  (frame.size.width - 220)*0.5/UIScreen.mainScreen.bounds.size.width,
                                                  220/UIScreen.mainScreen.bounds.size.height,
                                                  220/UIScreen.mainScreen.bounds.size.width)];
            _session = [[AVCaptureSession alloc] init];
            [_session setSessionPreset:AVCaptureSessionPresetHigh];
            if ([_session canAddInput:_input]) {
                [_session addInput:_input];
            }
            if ([_session canAddOutput:_output]) {
                [_session addOutput:_output];
            }
            _output.metadataObjectTypes = @[AVMetadataObjectTypeQRCode];
            _previewlayer = [AVCaptureVideoPreviewLayer layerWithSession:_session];
            _previewlayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
            _previewlayer.frame = self.layer.bounds;
            [self.layer insertSublayer:_previewlayer atIndex:0];
            [_session startRunning];
            
        }else{//相机不可用
            //实现相关提示框
        }
    }
    [self addSubview:self.hudView];
    return self;
}
#pragma mark - AVCaptureMetadataOutputObjectsDelegate
- (void)captureOutput:(AVCaptureOutput *)output didOutputMetadataObjects:(NSArray<__kindof AVMetadataObject *> *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
    if (metadataObjects.count > 0) {
        [_session stopRunning];
        AVMetadataMachineReadableCodeObject *metadataObject = metadataObjects.firstObject;
        !self.backQRCodeURL ? : self.backQRCodeURL(metadataObject.stringValue);
    }
}

#pragma mark - lazy
//懵层
- (UIView *)hudView
{
    if (!_hudView) {
        _hudView = [[UIView alloc] initWithFrame:self.bounds];
        CGFloat x = (self.frame.size.width - 220)*0.5;
        CGFloat y = (self.frame.size.height - 220)*0.5;
        CGFloat height = 220;
        //镂空
        CGRect qrRect = CGRectMake(x,y,height, height);
        UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:self.frame cornerRadius:0];
        UIBezierPath *circlePath = [UIBezierPath bezierPathWithRect:qrRect];
        [path appendPath:circlePath];
        [path setUsesEvenOddFillRule:YES];
        CAShapeLayer *fillLayer = [CAShapeLayer layer];
        fillLayer.path = path.CGPath;
        fillLayer.fillRule = kCAFillRuleEvenOdd;
        fillLayer.fillColor = [UIColor colorWithRed:0/255.0 green:0/255.0 blue:0/255.0 alpha:0.4].CGColor;
        fillLayer.opacity = 0.5;
        [_hudView.layer addSublayer:fillLayer];
        
        //白色矩形
        UIBezierPath *bezierPath = [UIBezierPath bezierPathWithRect:CGRectMake(x, y, height, height)];
        CAShapeLayer *shapLayer = [CAShapeLayer layer];
        shapLayer.backgroundColor = UIColor.clearColor.CGColor;
        shapLayer.path = bezierPath.CGPath;
        shapLayer.lineWidth = 0.5;
        shapLayer.strokeColor = UIColor.whiteColor.CGColor;
        shapLayer.fillColor = UIColor.clearColor.CGColor;
        [_hudView.layer addSublayer:shapLayer];
        
        //绿色四个角落
        UIBezierPath *cornerBezierPath = [UIBezierPath bezierPath];
        
        [cornerBezierPath moveToPoint:CGPointMake(x, y+30)];//左上角
        [cornerBezierPath addLineToPoint:CGPointMake(x, y)];
        [cornerBezierPath addLineToPoint:CGPointMake(x+30, y)];
        
        [cornerBezierPath moveToPoint:CGPointMake(x+height-30, y)];//右上角
        [cornerBezierPath addLineToPoint:CGPointMake(x+height, y)];
        [cornerBezierPath addLineToPoint:CGPointMake(x+height, y+30)];
        
        [cornerBezierPath moveToPoint:CGPointMake(x+height, y+height-30)];//左上角
        [cornerBezierPath addLineToPoint:CGPointMake(x+height, y+height)];
        [cornerBezierPath addLineToPoint:CGPointMake(x+height-30, y+height)];
        
        [cornerBezierPath moveToPoint:CGPointMake(x+30, y+height)];//左上角
        [cornerBezierPath addLineToPoint:CGPointMake(x, y+height)];
        [cornerBezierPath addLineToPoint:CGPointMake(x, y+height-30)];
        
        CAShapeLayer *cornerShapLayer = [CAShapeLayer layer];
        cornerShapLayer.backgroundColor = UIColor.clearColor.CGColor;
        cornerShapLayer.path = cornerBezierPath.CGPath;
        cornerShapLayer.lineWidth = 3.0;
        cornerShapLayer.strokeColor = STYLECOLOR.CGColor;
        cornerShapLayer.fillColor = UIColor.clearColor.CGColor;
        [_hudView.layer addSublayer:cornerShapLayer];
        
        //光标
        CAGradientLayer *gradientLayer = [CAGradientLayer layer];
        gradientLayer.frame = CGRectMake(x+3, y+3, height-6, 1.5);
        gradientLayer.colors = [self colorWithBasicColor:STYLECOLOR];
        gradientLayer.startPoint = CGPointMake(0, 0.5);
        gradientLayer.endPoint = CGPointMake(1.0, 0.5);
        [gradientLayer addAnimation:[self positionBasicAnimate] forKey:nil];
        [_hudView.layer addSublayer:gradientLayer];
    }
    return _hudView;
}
//动画
- (CABasicAnimation *)positionBasicAnimate
{
    CGFloat x = (self.frame.size.width - 220)*0.5;
    CGFloat y = (self.frame.size.height - 220)*0.5;
    CGFloat height = 220;
    CABasicAnimation *animate = [CABasicAnimation animationWithKeyPath:@"position"];
    animate.removedOnCompletion = NO;
    animate.duration = 2.0;
    animate.fillMode = kCAFillModeRemoved;
    animate.repeatCount = HUGE_VAL;
    animate.fromValue = [NSValue valueWithCGPoint:CGPointMake(x+height*0.5, y+3)];
    animate.toValue = [NSValue valueWithCGPoint:CGPointMake(x+height*0.5, y+height-3)];
    animate.autoreverses = YES;
    return animate;
}

- (NSArray<UIColor *> *)colorWithBasicColor:(UIColor *)basicCoclor
{
    CGFloat R, G, B, amplitude;
    amplitude = 90/255.0;
    NSInteger numComponents = CGColorGetNumberOfComponents(basicCoclor.CGColor);
    NSArray *colors;
    if (numComponents == 4)
    {
        const CGFloat *components = CGColorGetComponents(basicCoclor.CGColor);
        R = components[0];
        G = components[1];
        B = components[2];
        colors = @[(id)[UIColor colorWithWhite:0.667 alpha:0.2].CGColor,
                   (id)basicCoclor.CGColor,
                   (id)[UIColor colorWithRed:R+amplitude > 1.0 ? 1.0:R+amplitude
                                        green:G+amplitude > 1.0 ? 1.0:G+amplitude
                                        blue:B+amplitude > 1.0 ? 1.0:B+amplitude alpha:1.0].CGColor,
                   (id)[UIColor colorWithRed:R+amplitude > 1.0 ? 1.0:R+amplitude*2
                                        green:G+amplitude > 1.0 ? 1.0:G+amplitude*2
                                        blue:B+amplitude > 1.0 ? 1.0:B+amplitude*2 alpha:1.0].CGColor,
                   (id)[UIColor colorWithRed:R+amplitude > 1.0 ? 1.0:R+amplitude
                                        green:G+amplitude > 1.0 ? 1.0:G+amplitude
                                        blue:B+amplitude > 1.0 ? 1.0:B+amplitude alpha:1.0].CGColor,
                   (id)basicCoclor.CGColor,
                   (id)[UIColor colorWithWhite:0.667 alpha:0.2].CGColor,];
    }else{
        colors = @[(id)basicCoclor.CGColor,
                   (id)basicCoclor.CGColor,];
    }
    return colors;
}

注解

1. (instancetype)initWithFrame:(CGRect)frame
  • 该方法实现相关控件初始化和相机是否可用判断(硬件损坏和相机权限)
  • 这里没有实现相机不可用的提示,小伙伴们按照自己的需求添加一下
2. pragma mark - AVCaptureMetadataOutputObjectsDelegate
  • 这个方法是扫描成功之后的代理回调,这里停止扫描和block返回结果
3. 下面是相机前面的懵层视图懒加载
  • 内部实现了外部灰色加透明度和中部矩形框镂空
  • 白色矩形框的绘画
  • 四个角落和中部光标的绘画
  • 这些绘画中使用了UIBezierPath(贝塞尔曲线),CAShapeLayer,CAGradientLayer三个类,
  • 光标的移动使用了核心动画的CABasicAnimation类
4. (NSArray<UIColor *> *)colorWithBasicColor:(UIColor *)basicCoclor
  • 该方法使用颜色获取RBGA,基础上生成需要渐变的相关颜色,获取失败的话返回当前颜色

抽空上传了一下demo

结:有需要的小伙伴们可以直接复制过去就可以使用,无需其它修改,内部没有使用图片,都用贝塞尔曲线画的,如果有写的不好的地方小伙伴们也可以在评论区留言给我,我们一起探讨

相关文章

  • iOS开发:二维码扫描与生成(扫描篇)

    iOS开发中经常要用到生成二维码与扫描二维码的功能,iOS7开始,系统支持原生的扫描二维码,iOS7 扫描二维码可...

  • iOS 二维码扫描

    iOS开发中 二维码扫描 前言 在移动开发中二维码扫描这种事情越来越常见了,在iOS中我选择了用ZBar这个第三方...

  • iOS开发之二维码扫描

    iOS开发之二维码扫描 在 iOS7 以前,在IOS中实现二维码和条形码扫描,我们所知的有,两大开源组件 ZBar...

  • IOS二维码(ZXingObjc)

    IOS二维码(ZXingObjc) 前言 公司最近上线一款产品,是通过二维码扫描登录。开发阶段的时候使用的是IOS...

  • iOS APP原生一维码、二维码扫描使用介绍

    在app开发中,经常会遇到二维码扫描的功能。 今天我给大家介绍一下,iOS原生一维码、二维码扫描使用。简单实用 话...

  • iOS APP原生二维码使用介绍

    在app开发中,经常会遇到二维码扫描的功能。 今天我给大家介绍一下,iOS原生一维码、二维码扫描使用。简单实用 话...

  • ZBar

    iOS中使用ZBar扫描二维码自定义扫描界面

  • 二维码的生成与扫描

    在简书上看到内容就跟着做了一遍。做个记录。首先是二维码的扫描。iOS开发-二维码扫描这里需要用到的是AVFound...

  • 使用AVFoundation框架实现扫描二维码

    iOS 7之前,开发者开发扫描二维码功能时,一般会借助第三方库,常用的如ZBarSDK等。iOS 7之后,苹果官方...

  • IOS中生成二维码、扫描二维码

    title : IOS中生成二维码、扫描二维码category : UI IOS中生成二维码、保存二维码 标签(空...

网友评论

    本文标题:iOS开发之二维码扫描

    本文链接:https://www.haomeiwen.com/subject/sqhhxctx.html