iOS-长按识别二维码/生成二维码/扫描二维码

参考:http://www.jianshu.com/p/997cec333822

参考:https://github.com/nglszs/BCQRcode

方式一:长按识别二维码

#import "LYBLongPressRecognizeEwmVC.h"
#import "UIImageView+CreatCode.h"
/** 补充的iOS9新特性*/
#import <SafariServices/SafariServices.h>

@interface LYBLongPressRecognizeEwmVC ()

@end

@implementation LYBLongPressRecognizeEwmVC

- (void)viewDidLoad {
    [super viewDidLoad];

    [self createErweima];

    //长按识别图中的二维码,类似于微信里面的功能,前提是当前页面必须有二维码
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(readCode:)];
    [self.view addGestureRecognizer:longPress];
}

- (void)readCode:(UILongPressGestureRecognizer *)pressSender {
    if (pressSender.state ==UIGestureRecognizerStateBegan) {
        //截图再读取
        UIGraphicsBeginImageContextWithOptions(self.view.bounds.size,YES, 0);
        CGContextRef context =UIGraphicsGetCurrentContext();
        [self.view.layer renderInContext:context];
        UIImage *image =UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();

        //识别二维码
        CIImage *ciImage = [[CIImage alloc]initWithCGImage:image.CGImage options:nil];
        CIContext *ciContext = [CIContext contextWithOptions:@{kCIContextUseSoftwareRenderer : @(YES)}];//软件渲染
        CIDetector *detector = [CIDetector detectorOfType:CIDetectorTypeQRCode context:ciContext options:@{CIDetectorAccuracy :CIDetectorAccuracyHigh}];//二维码识别
        NSArray *features = [detector featuresInImage:ciImage];
        for (CIQRCodeFeature *feature in features) {
            NSLog(@"msg = %@",feature.messageString);//打印二维码中的信息
            if ([feature.messageString containsString:@"http"]) {
                //4.1 创建SafariVC
                SFSafariViewController *sfVC = [[SFSafariViewController         alloc] initWithURL:[NSURL URLWithString:feature.messageString]];
                //4.2 弹出SafariVC
                [self presentViewController:sfVC animated:YES completion:nil];
            }
        }
    }
}

//创建二维码
- (void)createErweima {
    UIImageView *imgV=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, WIDTH)];
    [self.view addSubview:imgV];
    [imgV creatCode:@"http://www.baidu.com" Image:nil andImageCorner:20];
}

@end

************生成二维码

 
 
#import <UIKit/UIKit.h>
 
NS_ASSUME_NONNULL_BEGIN
 
@interface UIImageView (CreatCode)

/**
  这里传入二维码的信息,image是加载二维码上方的图片,如果不要图片直接codeImage为nil即可,后面是图片的圆角
  */
-(void)creatCode:(NSString *)codeContent Image:(UIImage *)codeImage andImageCorner:(CGFloat)imageCorner;
 
@end
 
NS_ASSUME_NONNULL_END
*******
 
#import "UIImageView+CreatCode.h"
#define ImageSize self.bounds.size.width

@implementation UIImageView (CreatCode)

- (void)creatCode:(NSString *)codeContent Image:(UIImage *)codeImage andImageCorner:(CGFloat)imageCorner {
   //用CoreImage框架实现二维码的生成,下面方法最好异步调用
   dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
       CIFilter *codeFilter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
       //每次调用都恢复其默认属性
       [codeFilter setDefaults];
       NSData *codeData = [codeContent dataUsingEncoding:NSUTF8StringEncoding];
       //设置滤镜数据
       [codeFilter setValue:codeData forKey:@"inputMessage"];
       //获得滤镜输出的图片
       CIImage *outputImage = [codeFilter outputImage];
       //这里的图像必须经过位图转换,不然会很模糊
       UIImage *translateImage = [self creatUIImageFromCIImage:outputImage andSize:ImageSize];
       //这里如果不想设置圆角,直接传一个image就好了
       UIImage *resultImage = [self setSuperImage:translateImage andSubImage:[self
       imageCornerRadius:imageCorner andImage:codeImage]];
       dispatch_async(dispatch_get_main_queue(), ^{
            self.image = resultImage;
         });
   });
}
 
//这里的size我是用imageview的宽度来算的,你可以改为自己想要的size
- (UIImage *)creatUIImageFromCIImage:(CIImage *)image andSize:(CGFloat)size {
    //下面是创建bitmao没什么好解释的,不懂得自行百度或者参考官方文档
    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 colorRef = CGColorSpaceCreateDeviceGray();
    CGContextRef contextRef = CGBitmapContextCreate(nil, width, height, 8, 0, colorRef, (CGBitmapInfo)kCGImageAlphaNone);
    CIContext *context = [CIContext contextWithOptions:nil];
    CGImageRef imageRef = [context createCGImage:image fromRect:extent];
    CGContextSetInterpolationQuality(contextRef,kCGInterpolationNone);
    CGContextScaleCTM(contextRef, scale, scale);
    CGContextDrawImage(contextRef, extent, imageRef);
    CGImageRef newImage = CGBitmapContextCreateImage(contextRef);
    CGContextRelease(contextRef);
    CGImageRelease(imageRef);
    return [UIImage imageWithCGImage:newImage];
}
 
//这里将二维码上方的图片设置圆角并缩放
- (UIImage *)imageCornerRadius:(CGFloat)cornerRadius andImage:(UIImage *)image {
    //这里是将图片进行处理,frame不能太大,否则会挡住二维码
    CGRect frame = CGRectMake(0, 0,ImageSize/5, ImageSize/5);
    UIGraphicsBeginImageContextWithOptions(frame.size,NO, 0);
    [[UIBezierPath bezierPathWithRoundedRect:frame cornerRadius:cornerRadius] addClip];
    [image drawInRect:frame];
    UIImage *clipImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return clipImage;
}

- (UIImage *)setSuperImage:(UIImage *)superImage andSubImage:(UIImage *)subImage {
    //将两张图片绘制在一起
    UIGraphicsBeginImageContextWithOptions(superImage.size,YES, 0);
    [superImage drawInRect:CGRectMake(0, 0, superImage.size.width, superImage.size.height)];
    [subImage drawInRect:CGRectMake((ImageSize - ImageSize/5)/2, (ImageSize -ImageSize/5)/2, subImage.size.width, subImage.size.height)];
    UIImage *resultImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return resultImage;
}
 
@end

***************扫描二维码

#import <UIKit/UIKit.h>

#import <AVFoundation/AVFoundation.h>

@interface ScanCodeViewController :UIViewController<AVCaptureMetadataOutputObjectsDelegate>{
    AVCaptureSession * session;
    AVCaptureMetadataOutput * output;
    NSInteger lineNum;
    BOOL upOrDown;
    NSTimer *lineTimer;
}

@property (nonatomic,strong)UIImageView *lineImageView;
@property (nonatomic,strong)UIImageView *backImageView;

@end


#import "ScanCodeViewController.h"

@implementation ScanCodeViewController

- (void)viewDidLoad {
    [superviewDidLoad];
    if ([[[UIDevicecurrentDevice]systemVersion]floatValue] >= 7.0) {
       AVAuthorizationStatus authStatus =  [AVCaptureDeviceauthorizationStatusForMediaType:AVMediaTypeVideo];
       if (authStatus ==AVAuthorizationStatusDenied || authStatus ==AVAuthorizationStatusRestricted) {
            [[[UIAlertViewalloc]initWithTitle:nilmessage:@"本应用无访问相机的权限,如需访问,可在设置中修改"delegate:nilcancelButtonTitle:@"好的"otherButtonTitles:nil,nil]show];
            return;
       } else {
            //打开相机
            AVCaptureDevice * device = [AVCaptureDevicedefaultDeviceWithMediaType:AVMediaTypeVideo];
            //创建输入流
            AVCaptureDeviceInput * input = [AVCaptureDeviceInputdeviceInputWithDevice:deviceerror:nil];

            //创建输出流
            output = [[AVCaptureMetadataOutputalloc]init];
            //设置代理在主线程里刷新[outputsetMetadataObjectsDelegate:selfqueue:dispatch_get_main_queue()];
            //设置扫描区域,这个需要仔细调整
            [outputsetRectOfInterest:CGRectMake(64/BCHeight, (BCWidth - 320)/2/BCWidth, 320/BCHeight, 320/BCWidth)];

            //初始化链接对象
            session = [[AVCaptureSessionalloc]init];
            //高质量采集率
            [sessionsetSessionPreset:AVCaptureSessionPresetHigh];
            [sessionaddInput:input];
            [sessionaddOutput:output];
            //设置扫码支持的编码格式output.metadataObjectTypes=@[AVMetadataObjectTypeQRCode,AVMetadataObjectTypeEAN13Code,AVMetadataObjectTypeEAN8Code,AVMetadataObjectTypeCode128Code];
            AVCaptureVideoPreviewLayer * layer = [AVCaptureVideoPreviewLayerlayerWithSession:session];
            layer.videoGravity=AVLayerVideoGravityResizeAspectFill;
            layer.frame=self.view.layer.bounds;
            [self.view.layeraddSublayer:layer];
        }
    }
    [self_initView];
}

//里面所有的控件可以自己定制,这里只是简单的例子
- (void)_initView {
    //扫码框
    _backImageView = [[UIImageViewalloc]initWithFrame:CGRectMake(0, 64,BCWidth,BCHeight - 64)];
    _backImageView.image = [UIImageimageNamed:@"camera_bg"];
    [self.viewaddSubview:_backImageView];
    _lineImageView = [[UIImageViewalloc]initWithFrame:CGRectMake(16, 15,BCWidth - 32, 1)];
    _lineImageView.backgroundColor = [UIColororangeColor];
    [_backImageViewaddSubview:_lineImageView];
    //各种参数设置
    lineNum = 0;
    upOrDown =NO;
    lineTimer = [NSTimerscheduledTimerWithTimeInterval:0.01target:selfselector:@selector(lineAnimation)userInfo:nilrepeats:YES];
}

- (void)lineAnimation {
    if (upOrDown ==NO) {
        lineNum ++;
        _lineImageView.frame =CGRectMake(CGRectGetMinX(_lineImageView.frame), 15 + lineNum, BCWidth - 32, 1);
        CGFloat tempHeight =CGRectGetHeight(_backImageView.frame) * 321/542;
        NSInteger height = (NSInteger)tempHeight + 20;
        if (lineNum == height) {
            upOrDown =YES;
        }
    }
    else {
        lineNum --;
        _lineImageView.frame =CGRectMake(CGRectGetMinX(_lineImageView.frame), 15 + lineNum, BCWidth - 32, 1);
        if (lineNum == 0) {
            upOrDown =NO;
        }
    }
}

#pragma mark AVCaptureMetadataOutputObjectsDelegate
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection {
    if ([metadataObjectscount] > 0) {
        [sessionstopRunning];//停止扫码
        AVMetadataMachineReadableCodeObject *metadataObject = [metadataObjectsfirstObject];
        ResultViewController *resultVC = [[ResultViewControlleralloc]init];
        resultVC.contentString = metadataObject.stringValue;
        [self.navigationControllerpushViewController:resultVCanimated:NO];
    }
}

- (void)viewWillAppear:(BOOL)animated {
    [superviewWillAppear:animated];
    [sessionstartRunning];
    [lineTimersetFireDate:[NSDatedistantPast]];
}

- (void)viewWillDisappear:(BOOL)animated {
    [superviewWillDisappear:animated];
    [sessionstopRunning];
    [lineTimersetFireDate:[NSDatedistantFuture]];
    if (![self.navigationController.viewControllers containsObject:self]) {//释放timer
        [lineTimerinvalidate];
        lineTimer =nil;
    }
}

- (void)dealloc {
    NSLog(@"已释放");
}

@end

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值