tom实用轮子iOS Developer

二维码扫描和二维码图片识别封装

2017-02-26  本文已影响407人  ZhengYaWei

之前写过文章介绍过苹果原生CoreImage框架的使用,如何用来生成二维码和扫描二维码http://www.jianshu.com/p/0884c3d83405 。 以前封装了一个二维码扫描和二维码识别的界面,前几天给稍微整理了下。文章目的主要介绍封装思路。Demo下载地址:https://github.com/ZhengYaWei1992/ZWQRCode 具体请看效果图。

效果图

具体如何识别相册中的图片功能,就不展示了,相册中包含个人隐私😀。
源码分析:
这里我主要是创建了两个类ZWQRCodeReaderView和ZWQRCodeController,前者主要负责处理二维码扫面界面的显示,ZWQRCodeController主要负责一些业务逻辑的处理,使用的时候只要模态弹出该视图控制器即可,之后再实现如下代理方法,直接获取扫面结果:

#pragma mark -ZWQRCodeControllerDelegate
//模仿微信一般是扫描成功后,会从当前页面跳转过去,所以一般会设置一个代理
- (void)qrcodeController:(ZWQRCodeController *)qrcodeController readerScanResult:(NSString *)readerScanResult type:(ZWQRCodeResultType)resultType{
   /*
    ZWQRCodeResultTypeSuccess = 0, // 1.成功获取图片中的二维码信息
    ZWQRCodeResultTypeNoInfo = 1,  // 2.识别的图片没有二维码信息
    ZWQRCodeResultTypeError = 2   // 3.其他错误
    */
   if (resultType == ZWQRCodeResultTypeSuccess) {
       NSLog(@"%@",readerScanResult);
       if ([readerScanResult hasPrefix:@"http"]) {
           [[UIApplication sharedApplication] openURL:[NSURL URLWithString:readerScanResult]];
       }
   }
}

关于如何扫描二维码相关代码不再j介绍,具体请看之前的文章,二维码扫面使用起来很简单。重点是类似这样的界面如何搭建,尤其是中间的一块透明区域,边上的朦胧效果。可能有人会说是通过UI给的特殊图片就可以实现的。其实并不是这样的。主要是借助神奇的CAShapeLayer和贝塞尔的完美结合。首先ZWQRCodeReaderView这个类的实例对象中,添加一个UIView(_viewMask)并将背景色整体设置为灰蒙蒙的状态,之后再挖空中间的部分,实现代码如下。注意这行代码是关键:bezierPathByReversingPath

UIBezierPath *path = [UIBezierPath bezierPath];
        [path appendPath:[UIBezierPath bezierPathWithRect:_viewMask.bounds]];
        //有效扫描区的图片显示和全透明区域完全重合
        //如果将.bezierPathByReversingPath则不会产生中间全透明部分
        [path appendPath:[UIBezierPath bezierPathWithRect:self.rectScanZone].bezierPathByReversingPath];
        CAShapeLayer *maskLayer = [CAShapeLayer layer];
        maskLayer.path = path.CGPath;
        _viewMask.layer.mask = maskLayer;

关于如何布局。
如果不通过约束来布局,也不借助第三方约束框架,这样的界面该如何布局以适配不同尺寸的设备,其实这里面也是很有技巧的。主要是借助一个比例来设置frame值,而不是具体的数值。将屏幕的宽度320段等比划分,之后布局的话,主要借助ZW_QRCODE_WidthRate这个宏。

#define ZW_QRCODE_ScreenWidth  CGRectGetWidth([UIScreen mainScreen].bounds)
#define ZW_QRCODE_WidthRate    ZW_QRCODE_ScreenWidth/320

关于如何识别相册中图片的二维码。识别图片中的二维码主要借助CIDetector这个类。

- (CIDetector *)detector
{
    if (!_detector) {
        _detector = [CIDetector detectorOfType:CIDetectorTypeQRCode context:nil options:@{ CIDetectorAccuracy : CIDetectorAccuracyHigh }];
    }
    return _detector;
}

从系统相册中选中图片后,主要通过 NSArray *features = [self.detector featuresInImage:[CIImage imageWithCGImage:image.CGImage]];这行代码获取识别信息,相关识别信息都包含在这个数组中,剩下的信息处理逻辑就和普通扫面二维码识别逻辑一样的。

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    // 1.获取图片信息
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    if (!image){
        image = [info objectForKey:UIImagePickerControllerOriginalImage];
    }
    
    // 2.退出图片控制器
    [picker dismissViewControllerAnimated:YES completion:^{
        
        [[UIApplication sharedApplication]setStatusBarStyle:UIStatusBarStyleLightContent];
        
        NSArray *features = [self.detector featuresInImage:[CIImage imageWithCGImage:image.CGImage]];
        if (features.count) { // 1.识别到二维码
            // 1.播放提示音
            SystemSoundID soundID;
            NSString *strSoundFile = [[NSBundle zw_qrCodeBundle] pathForResource:@"noticeMusic" ofType:@"wav"];
            AudioServicesCreateSystemSoundID((__bridge CFURLRef)[NSURL fileURLWithPath:strSoundFile],&soundID);
            AudioServicesPlaySystemSound(soundID);
            
            // 2.显示扫描结果信息
            CIQRCodeFeature *feature = [features objectAtIndex:0];
            //            [ZWQRCodeAlert showWithTitle:feature.messageString];
            
            if ([self.delegate respondsToSelector:@selector(qrcodeController:readerScanResult:type:)]) {
                [self.delegate qrcodeController:self readerScanResult:feature.messageString type:ZWQRCodeResultTypeSuccess];
                //扫描到结果后,直接返回,不要设置动画返回
                [self dismissViewControllerAnimated:YES completion:^{}];
            }
        }else {
            [ZWQRCodeAlert showWithTitle:@"没有识别到二维码信息"];
        }
    }];
}

关于如何控制闪光灯开关。

#pragma mark- Action
//闪光灯按钮点击事件
- (void)turnTorchEvent:(UIButton *)button{
    button.selected = !button.selected;
    Class captureDeviceClass = NSClassFromString(@"AVCaptureDevice");
    if (captureDeviceClass != nil) {
        AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
        if ([device hasTorch] && [device hasFlash]){
            
            [device lockForConfiguration:nil];
            if (button.selected) {
                [device setTorchMode:AVCaptureTorchModeOn];
                [device setFlashMode:AVCaptureFlashModeOn];
            } else {
                [device setTorchMode:AVCaptureTorchModeOff];
                [device setFlashMode:AVCaptureFlashModeOff];
            }
            [device unlockForConfiguration];
        }
    }
}

上一篇下一篇

猜你喜欢

热点阅读