iOS 二维码生成和扫描

一、二维码生成

    //创建二维码视图
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(50, 100, 200, 200)];
    [self.view addSubview:imageView];
    //二维码中间图片 (如果没有中间图片可屏蔽)
    UIImageView *sjhImageView = [[UIImageView alloc]initWithFrame:CGRectMake((imageView.frame.size.width- 50)/2, (imageView.frame.size.height - 50)/2, 50, 50)];
    sjhImageView.image = [UIImage imageNamed:@"sunjunhua"];
    [imageView addSubview:sjhImageView];

// 1.创建过滤器
    CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    // 2.恢复默认
    [filter setDefaults];
    // 3.给过滤器添加数据
    NSString *dataString = @"我爱你,么么哒!";
    NSData *data = [dataString dataUsingEncoding:NSUTF8StringEncoding];
    // 4.通过KVO设置滤镜inputMessage数据
    [filter setValue:data forKeyPath:@"inputMessage"];
    // 4.获取输出的二维码
    CIImage *outputImage = [filter outputImage];
    // 5.将CIImage转换成UIImage,并放大显示 
    imageView.image = [self createNonInterpolatedUIImageFormCIImage:outputImage withSize:300];

因为正常系统生成的二位吗很模糊不清晰,下面这个方法是让二维码处于高清状态。//高清二维码

- (UIImage *)createNonInterpolatedUIImageFormCIImage:(CIImage *)image withSize:(CGFloat) size {
    CGRect extent = CGRectIntegral(image.extent);
    //设置比例
    CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
    // 创建bitmap(位图);
    size_t width = CGRectGetWidth(extent) * scale;
    size_t height = CGRectGetHeight(extent) * scale;
    CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
    CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (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);
    // 保存bitmap到图片
    CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
    CGContextRelease(bitmapRef);
    CGImageRelease(bitmapImage);
    return [UIImage imageWithCGImage:scaledImage];
}


二、二维码扫描

2.1.这里要签协议AVCaptureMetadataOutputObjectsDelegate

 // 获取 AVCaptureDevice 实例
    AVCaptureDevice *captureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    // 初始化输入流
    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:captureDevice error:nil];
    // 创建会话
    _session = [[AVCaptureSession alloc] init];
    //高质量采集率
    [_session setSessionPreset:AVCaptureSessionPresetHigh];
    // 初始化输出流
    AVCaptureMetadataOutput *output = [[AVCaptureMetadataOutput alloc] init];
    //代理
    [output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    
    CGFloat x = ((kScreenHeight-Width-64)/2.0)/kScreenHeight;
    CGFloat y = ((kScreenWidth-Width)/2.0)/kScreenWidth;
    CGFloat width = Width/kScreenHeight;
    CGFloat height = Width/kScreenWidth;
    output.rectOfInterest = CGRectMake(x, y, width, height);
    
    if ([_session canAddInput:input]) {
        // 添加输入流
        [_session addInput:input];
    }
    if ([_session canAddOutput:output]) {
        // 添加输出流
        [_session addOutput:output];
    }
    
    //设置二维码类型  (下面几个类型是 二维码、条形码都兼容,如果需要其他类型还需添加)
    output.metadataObjectTypes =@[AVMetadataObjectTypeQRCode,AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code];
    
    //添加扫描画面
    _previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:_session];
    [_previewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
    [_previewLayer setFrame:self.view.layer.bounds];
    [self.view.layer addSublayer:_previewLayer];
    // 开始会话
    [_session startRunning];

2.2实现代理方法

- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection{
    NSString *stringValue;
    if ([metadataObjects count] >0){
        //停止扫描
        [_session stopRunning];
        //删除预览图层
//        [self.previewLayer removeFromSuperlayer];
        AVMetadataMachineReadableCodeObject * metadataObject = [metadataObjects objectAtIndex:0];

        //扫描结果

        stringValue = metadataObject.stringValue;
        //根据需求处理结果
        //初始化提示框;
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"扫描结果" message:stringValue preferredStyle: UIAlertControllerStyleAlert];
        
        [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }]];
        
        //弹出提示框;
        [self presentViewController:alert animated:true completion:nil];


三、选取相册中二维码扫描

3.1 需要在info.plist中添加相册权限   NSPhotoLibraryUsageDescription

3.2 签协议UINavigationControllerDelegate,UIImagePickerControllerDelegate

3.3 在需要相册功能按钮中实现

 UIImagePickerController *imagrPicker = [[UIImagePickerController alloc]init];
    imagrPicker.delegate = self;
    imagrPicker.allowsEditing = YES;
    //将来源设置为相册
    imagrPicker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
    
    [self presentViewController:imagrPicker animated:YES completion:nil];

3.4 实现代理方法

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    //获取选中的照片
    UIImage *image = info[UIImagePickerControllerEditedImage];
    
    if (!image) {
        image = info[UIImagePickerControllerOriginalImage];
    }
    //初始化  将类型设置为二维码
    CIDetector *detector = [CIDetector detectorOfType:CIDetectorTypeQRCode context:nil options:nil];
    
    [picker dismissViewControllerAnimated:YES completion:^{
        //设置数组,放置识别完之后的数据
        NSArray *features = [detector featuresInImage:[CIImage imageWithData:UIImagePNGRepresentation(image)]];
        //判断是否有数据(即是否是二维码)
        if (features.count >= 1) {
            //取第一个元素就是二维码所存放的文本信息
            CIQRCodeFeature *feature = features[0];
            NSString *scannedResult = feature.messageString;
            //通过对话框的形式呈现
            [self alertControllerMessage:scannedResult];
        }else{ 

           //通过对话框的形式呈现

            [self alertControllerMessage:@"这不是一个二维码"];
        }
    }];
}
四、二维码扫描动画(你懂得)

 
   
UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake((kScreenWidth-Width)/2.0, (kScreenHeight-Width-64)/2.0, Width, Width)];
    imageView.image = [UIImage imageNamed:@"scanscanBg"];
    
    [self.view addSubview:imageView];
    
    
    UIImageView *animationView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"scanLine"]];
    
    animationView.frame = CGRectMake(0,0, Width, 10);
    CABasicAnimation *animation = [CABasicAnimation animation];
    
    animation.keyPath =@"transform.translation.y";
    
    animation.byValue = @(Width-5);
    
    animation.removedOnCompletion = NO;
    
    animation.duration = 2.0;
    
    animation.repeatCount = MAXFLOAT;
    
    [animationView.layer addAnimation:animation forKey:nil];
    
    [imageView addSubview:animationView];

五、扫描区域外部视图(朦朦胧胧的感觉)

 //设置统一的视图颜色和视图的透明度
    UIColor *color = [UIColor blackColor];
    float alpha = 0.6;
    
    //设置扫描区域外部上部的视图
    UIView *topView = [[UIView alloc]init];
    topView.frame = CGRectMake(0, 64, kScreenWidth, (kScreenHeight-64-Width)/2.0-64);
    topView.backgroundColor = color;
    topView.alpha = alpha;
    
    //设置扫描区域外部左边的视图
    UIView *leftView = [[UIView alloc]init];
    leftView.frame = CGRectMake(0, 64+topView.frame.size.height, (kScreenWidth-Width)/2.0,Width);
    leftView.backgroundColor = color;
    leftView.alpha = alpha;
    
    //设置扫描区域外部右边的视图
    UIView *rightView = [[UIView alloc]init];
    rightView.frame = CGRectMake((kScreenWidth-Width)/2.0+Width,64+topView.frame.size.height, (kScreenWidth-Width)/2.0,Width);
    rightView.backgroundColor = color;
    rightView.alpha = alpha;
    
    //设置扫描区域外部底部的视图
    UIView *botView = [[UIView alloc]init];
    botView.frame = CGRectMake(0, 64+Width+topView.frame.size.height,kScreenWidth,kScreenHeight-64-Width-topView.frame.size.height);
    botView.backgroundColor = color;
    botView.alpha = alpha;
    
    //将设置好的扫描二维码区域之外的视图添加到视图图层上
    [self.view addSubview:topView];
    [self.view addSubview:leftView];
    [self.view addSubview:rightView];
    [self.view addSubview:botView];


总结:都是查资料和自己的总结,第一次写,比较Low,忘见谅,只是参考。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值