二维码生成/扫描

调用摄像头和相册,需要在plist文件里增加键值对:
Privacy - Camera Usage Description 如果不允许,您将无法使用摄像头
Privacy - Photo Library Usage Description 如果不允许,您将无法使用相册

- (void)createView {
    //生成按钮
    UIButton *createBtn = [[UIButton alloc]initWithFrame:CGRectMake(kScaleX*40, kScaleY*450, kScaleX*100, kScaleY*60)];
    [createBtn setTitle:@"生成" forState:UIControlStateNormal];
    [createBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    createBtn.titleLabel.font = [UIFont fontWithName:LightFont size:18];
    createBtn.backgroundColor = [UIColor blackColor];
    createBtn.layer.cornerRadius = 4;
    createBtn.clipsToBounds = YES;
    [createBtn addTarget:self action:@selector(createAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:createBtn];
    
    //扫描按钮
    UIButton *scannerBtn = [[UIButton alloc]initWithFrame:CGRectMake(kScaleX*235, kScaleY*450, kScaleX*100, kScaleY*60)];
    [scannerBtn setTitle:@"扫描" forState:UIControlStateNormal];
    [scannerBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    scannerBtn.titleLabel.font = [UIFont fontWithName:LightFont size:18];
    scannerBtn.backgroundColor = [UIColor blackColor];
    scannerBtn.layer.cornerRadius = 4;
    scannerBtn.clipsToBounds = YES;
    [scannerBtn addTarget:self action:@selector(scannerAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:scannerBtn];
}

生成:

- (void)createAction {
    //1.创建滤镜
    CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    
    //2.恢复默认
    [filter setDefaults];
    
    //3.给滤镜添加数据
    NSString *dataString = @"你好,世界";
    //将数据转换成NSData类型
    NSData *data = [dataString dataUsingEncoding:NSUTF8StringEncoding];
    //通过KVC设置滤镜的二维码输入信息
    [filter setValue:data forKey:@"inputMessage"];
    
    //4.获取输出的二维码图片(CIImage类型)
    CIImage *outImage = [filter outputImage];
    //将CIImage类型的图片装换成UIImage类型的图片
    UIImage *image = [self excludeFuzzyImageFromCIImage:outImage size:kScaleY*200];
    
    //5.显示二维码图片
    UIImageView *imageV = [[UIImageView alloc]initWithFrame:CGRectMake(kScaleX*87.5, 64+kScaleY*40, kScaleX*200, kScaleY*200)];
    imageV.image = image;
    [self.view addSubview:imageV];
}
#pragma mark -- 对图像进行清晰处理,很关键!
- (UIImage *)excludeFuzzyImageFromCIImage:(CIImage *)image size:(CGFloat)size {
    
    CGRect extent = CGRectIntegral(image.extent);
    
    //通过比例计算,让最终的图像大小合理(正方形是我们想要的)
    CGFloat scale = MIN(size / CGRectGetWidth(extent), size / CGRectGetHeight(extent));
    
    size_t width = CGRectGetWidth(extent) * scale;
    
    size_t height = CGRectGetHeight(extent) * scale;
    
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();
    
    CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, colorSpace, (CGBitmapInfo)kCGImageAlphaNone);
    
    CIContext * context = [CIContext contextWithOptions: nil];
    
    CGImageRef bitmapImage = [context createCGImage: image fromRect: extent];
    
    CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
    
    CGContextScaleCTM(bitmapRef, scale, scale);
    
    CGContextDrawImage(bitmapRef, extent, bitmapImage);
    
    CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
    
    //切记ARC模式下是不会对CoreFoundation框架的对象进行自动释放的,所以要我们手动释放
    CGContextRelease(bitmapRef);
    
    CGImageRelease(bitmapImage);
    
    CGColorSpaceRelease(colorSpace);
    
    return [UIImage imageWithCGImage: scaledImage];
}

扫描:

import <AVFoundation/AVFoundation.h>

遵守<AVCaptureMetadataOutputObjectsDelegate>协议,用于处理采集信息
使用到的全局变量:

@implementation ScannerViewController
{
    AVCaptureSession *session;//输入输出的中间桥梁
    NSTimer *timer;
    UIImageView *line;
}
- (void)scannerAction {
    //先判断摄像头硬件是否好用
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        //用户是否允许摄像头使用
        NSString *mediaType = AVMediaTypeVideo;
        AVAuthorizationStatus authorizationStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
        //不允许弹出提示框
        if (authorizationStatus == AVAuthorizationStatusRestricted || authorizationStatus == AVAuthorizationStatusDenied) {
            UIAlertController *alertView = [UIAlertController alertControllerWithTitle:@"摄像头访问受限" message:nil preferredStyle:UIAlertControllerStyleAlert];
            [self presentViewController:alertView animated:YES completion:nil];
            UIAlertAction *action = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                [self.navigationController popViewControllerAnimated:YES];
            }];
            [alertView addAction:action];
        }else {
            //这里是摄像头可以使用的处理逻辑
            [self addCamera];
        }
    }else {
        // 硬件问题提示
        UIAlertController *alertView = [UIAlertController alertControllerWithTitle:@"手机摄像头设备损坏" message:@"" preferredStyle:UIAlertControllerStyleAlert];
        [self presentViewController:alertView animated:YES completion:nil];
    }
}
- (void)addCamera {
    //获取摄像设备
    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(UI_SCREEN_WIDTH/375*37.5, 64+UI_SCREEN_HEIGHT/667*70, UI_SCREEN_WIDTH/375*300, UI_SCREEN_HEIGHT/667*300);
    CGFloat p1 = size.height/size.width;
    CGFloat p2 = 1920./1080.;  //使用了1080p的图像输出
    if (p1 < p2) {
        CGFloat fixHeight = self.view.bounds.size.width * 1920. / 1080.;
        CGFloat fixPadding = (fixHeight - size.height)/2;
        output.rectOfInterest = CGRectMake((cropRect.origin.y + fixPadding)/fixHeight,
                                           cropRect.origin.x/size.width,
                                           cropRect.size.height/fixHeight,
                                           cropRect.size.width/size.width);
    }else {
        CGFloat fixWidth = self.view.bounds.size.height * 1080. / 1920.;
        CGFloat fixPadding = (fixWidth - size.width)/2;
        output.rectOfInterest = CGRectMake(cropRect.origin.y/size.height,
                                           (cropRect.origin.x + fixPadding)/fixWidth,
                                           cropRect.size.height/size.height,
                                           cropRect.size.width/fixWidth);
    }
    //设置代理 在主线程里刷新
    [output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    
    //初始化链接对象
    session = [[AVCaptureSession alloc]init];
    //高质量采集率
    [session setSessionPreset:AVCaptureSessionPresetHigh];
    
    [session addInput:input];
    [session addOutput:output];
    //设置扫码支持的编码格式(如下设置条形码和二维码兼容)
    output.metadataObjectTypes = @[AVMetadataObjectTypeQRCode,AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code];
    
    AVCaptureVideoPreviewLayer *layer = [AVCaptureVideoPreviewLayer layerWithSession:session];
    layer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    layer.frame = self.view.layer.bounds;
    [self.view.layer insertSublayer:layer atIndex:0];
    
    [self creatScannerUI];
    
    [self lineMove];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(lineMove) name:@"move" object:nil];
    
    //开始捕获
    [session startRunning];
}

扫描UI:

- (void)creatScannerUI {
    //扫码窗口
    UIView *maskView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, UI_SCREEN_WIDTH, UI_SCREEN_HEIGHT-64)];
    
    maskView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.5];
    
    [self.view addSubview:maskView];
    
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRect:CGRectMake(0, 0, UI_SCREEN_WIDTH, UI_SCREEN_HEIGHT)];
    
    [maskPath appendPath:[[UIBezierPath bezierPathWithRoundedRect:CGRectMake(UI_SCREEN_WIDTH/375*67.5, UI_SCREEN_HEIGHT/667*100, UI_SCREEN_WIDTH/375*240, UI_SCREEN_HEIGHT/667*240) cornerRadius:1] bezierPathByReversingPath]];
    
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    
    maskLayer.path = maskPath.CGPath;
    
    maskView.layer.mask = maskLayer;
    
    //扫描动画
    line = [[UIImageView alloc]initWithFrame:CGRectMake(UI_SCREEN_WIDTH/375*67.5, 64+UI_SCREEN_HEIGHT/667*100, UI_SCREEN_WIDTH/375*240, 2)];
    line.image = [UIImage imageNamed:@"扫描线"];
    line.center = CGPointMake(UI_SCREEN_WIDTH/2, 64+UI_SCREEN_HEIGHT/667*100);
    [self.view addSubview:line];
    
    UIImageView *borderImg = [[UIImageView alloc]initWithFrame:CGRectMake(UI_SCREEN_WIDTH/375*67.5, 64+UI_SCREEN_HEIGHT/667*100, UI_SCREEN_WIDTH/375*240, UI_SCREEN_HEIGHT/667*240)];
    borderImg.image = [UIImage imageNamed:@"扫描框"];
    [self.view addSubview:borderImg];
}

//动画
- (void)lineMove {
    [UIView animateWithDuration:2.5 delay:0.0 options:UIViewAnimationOptionRepeat animations:^{
        line.center = CGPointMake(UI_SCREEN_WIDTH/2, 64+UI_SCREEN_HEIGHT/667*338);
    } completion:nil];
    [[NSNotificationCenter defaultCenter]postNotificationName:@"move" object:nil];
}
//扫码代理
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection {
    if (metadataObjects.count>0) {
        //[session stopRunning];
        AVMetadataMachineReadableCodeObject * metadataObject = [metadataObjects objectAtIndex :0];
        //输出扫描字符串
        NSLog(@"%@",metadataObject.stringValue);
    }
}
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 213,014评论 6 492
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,796评论 3 386
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 158,484评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,830评论 1 285
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,946评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,114评论 1 292
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,182评论 3 412
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,927评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,369评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,678评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,832评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,533评论 4 335
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,166评论 3 317
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,885评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,128评论 1 267
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,659评论 2 362
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,738评论 2 351

推荐阅读更多精彩内容