iOS开发之二维码扫描

这段时间用到了二维码扫描,用一个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

结:有需要的小伙伴们可以直接复制过去就可以使用,无需其它修改,内部没有使用图片,都用贝塞尔曲线画的

如果我的文章对小伙伴有帮助的话赏小编一瓶矿泉水💰呗,非常感谢

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 202,723评论 5 476
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,080评论 2 379
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 149,604评论 0 335
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,440评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,431评论 5 364
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,499评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,893评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,541评论 0 256
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,751评论 1 296
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,547评论 2 319
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,619评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,320评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,890评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,896评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,137评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,796评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,335评论 2 342