系统方法实现仿微信、支付宝二维码扫描 实现 (限制扫描区域、相机背景)

.h文件中做的事情:

//

//  FindSweepCodeViewController.h

//  Toon

//

//  Created by liguoting on 14/11/3.

//  Copyright (c) 2014 syswin. All rights reserved.

//


#import "BaseViewController.h"

#import <UIKit/UIKit.h>

#import <AVFoundation/AVFoundation.h>

#import "ActivityDetailViewController.h"

#import "ActivityInfoModel.h"

@interface FindSweepCodeViewController : BaseViewController<AVCaptureMetadataOutputObjectsDelegate>

{

    int num;

    BOOL upOrDown;

    NSTimer *timer;

}

@property (strong,nonatomic)AVCaptureDevice *device;

@property (strong,nonatomic)AVCaptureDeviceInput *input;

@property (strong,nonatomic)AVCaptureMetadataOutput *output;

@property (strong,nonatomic)AVCaptureSession *session;

@property (strong,nonatomic)AVCaptureVideoPreviewLayer *preview;

@property (nonatomic, retain) UIImageView *line;

@end




.m中:

//

//  FindSweepCodeViewController.m

//  Toon

//

//  Created by liguoting on 14/11/3.

//  Copyright (c) 2014 syswin. All rights reserved.

//


#import "FindSweepCodeViewController.h"

#import "SweepResultViewController.h"

#import "CardOwnerController.h"



@interface FindSweepCodeViewController ()

{

    NSString *_cardId;

    NSString *_userId;

    NSString *_activityId;

}


@end


@implementation FindSweepCodeViewController


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil

{

    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];

    if (self) {

        // Custom initialization

    }

    return self;

}


- (void)viewDidLoad

{

    [super viewDidLoad];

    self.navigationItem.title = @"二维码";

    self.view.backgroundColor = [UIColor whiteColor];

//    UIButton * scanButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];

//    [scanButton setTitle:@"取消" forState:UIControlStateNormal];

//    scanButton.frame = CGRectMake(100, 420, 120, 40);

//    [scanButton addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];

//    [self.view addSubview:scanButton];

    

    UILabel * labIntroudction= [[UILabel alloc] initWithFrame:CGRectMake((ScreenFrameWith-240)/2, 256, 240, 40)];

    labIntroudction.backgroundColor = [UIColor clearColor];

    labIntroudction.font = [UIFont systemFontOfSize:15];

    labIntroudction.textAlignment = NSTextAlignmentCenter;

    labIntroudction.numberOfLines=1;

    labIntroudction.textColor=[UIColor whiteColor];

    labIntroudction.text=@"将二维码放到框内即可自动扫描";

    [self.view addSubview:labIntroudction];

    

    

    UIImageView * imageView = [[UIImageView alloc]initWithFrame:CGRectMake((ScreenFrameWith-180)/2, 43, 180, 183)];

    imageView.image = [UIImage imageNamed:@"sweap_box"];

    [self.view addSubview:imageView];

    

    upOrDown = NO;

    num =0;

    

    /**

     此块代码为扫描先上下滑动的效果,此处需求不要

     

     :returns: return value description

     */

    self.line = [[UIImageView alloc] initWithFrame:CGRectMake((ScreenFrameWith-180)/2, 43, 180, 4)];

    self.line.image = [UIImage imageNamed:@"sweap_line"];

    [self.view addSubview:self.line];

    

    timer = [NSTimer scheduledTimerWithTimeInterval:.02 target:self selector:@selector(animation1) userInfo:nil repeats:YES];


    // Do any additional setup after loading the view from its nib.

    //创建返回首页按钮

    self.navigationItem.leftBarButtonItem =  [ISSUtility barButtonItemWithTarget:self action:@selector(backBttnClickDown) normalImage:@"header_icon_back.png" highLightImage:@"header_icon_back.png" title:nil titleColor:nil frame:CGRectMake(0,0,40,40)];


}


-(void)animation1

{

    if (upOrDown == NO) {

        num ++;

        self.line.frame = CGRectMake((ScreenFrameWith-180)/2, 43+2*num, 180, 2);

        if (2*num >= 180) {

            upOrDown = YES;

        }

    }

    else {

        num --;

        self.line.frame = CGRectMake((ScreenFrameWith-180)/2, 43+2*num, 180, 2);

        if (num == 0) {

            upOrDown = NO;

        }

    }

    

}


#pragma mark ------按钮点击事件--------

-(void)backBttnClickDown

{

    [self.navigationController popViewControllerAnimated:YES];

}


-(void)backAction

{

    

    [self.navigationController popViewControllerAnimated:YES];

    [timer invalidate];

}


-(void)viewWillAppear:(BOOL)animated

{

    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];

    

    if (authStatus == AVAuthorizationStatusDenied)

    {

        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"无法访问通讯录" message:@"请到设置->隐私->相机中将toon设置为允许访问相机!" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];

            [alert show];

    

    }else

    {

    

    [self setupCamera];

    }

    

}


#pragma mark ----alertView的代理-------

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex

{

     [self.navigationController popViewControllerAnimated:YES];

}

- (void)setupCamera

{

  

    // Device

    _device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];

    

    if(_device == nil)

    {

        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"未检测到相机" message:@"请检查相机设备是否正常" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];

        [alert show];

        return ;

    }

    // Input

    _input = [AVCaptureDeviceInput deviceInputWithDevice:self.device error:nil];

    

    // Output

    _output = [[AVCaptureMetadataOutput alloc]init];

    [_output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];

    //限制扫描区域(上左下右)

  //  [ _output setRectOfInterest : CGRectMake ( 43 / ScreenFrameHeight ,(( ScreenFrameWith - 180 )/ 2 )/ ScreenFrameWith , 183 /ScreenFrameHeight , 180 / ScreenFrameWith)];

     [ _output setRectOfInterest : CGRectMake ( 43 / ScreenFrameHeight ,(( ScreenFrameWith - 150 )/ 2 )/ ScreenFrameWith , 213 /ScreenFrameHeight , 210 / ScreenFrameWith)];

  //  [ _output setRectOfInterest : CGRectMake (0.5 ,0.5,0.5 , 0.5)];

    

    // Session

    _session = [[AVCaptureSession alloc]init];

    [_session setSessionPreset:AVCaptureSessionPresetHigh];

    if ([_session canAddInput:self.input])

    {

        [_session addInput:self.input];

    }

    

    if ([_session canAddOutput:self.output])

    {

        [_session addOutput:self.output];

    }

    

    // 条码类型 AVMetadataObjectTypeQRCode

    _output.metadataObjectTypes =@[AVMetadataObjectTypeQRCode];

    

    // Preview

    _preview =[AVCaptureVideoPreviewLayer layerWithSession:self.session];

    _preview.videoGravity = AVLayerVideoGravityResizeAspectFill;

    //_preview.frame =CGRectMake((ScreenFrameWith-180)/2,44,180,182);

     _preview.frame =CGRectMake(0,0,ScreenFrameWith,ScreenFrameHeight-44);

    [self.view.layer insertSublayer:self.preview atIndex:0];

    // Start

    [_session startRunning];

}

#pragma mark AVCaptureMetadataOutputObjectsDelegate

- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection

{

    

    NSString *stringValue;

    

    if ([metadataObjects count] >0)

    {

        AVMetadataMachineReadableCodeObject * metadataObject = [metadataObjects objectAtIndex:0];

        stringValue = metadataObject.stringValue;

        

    }

    

    [_session stopRunning];

    //[self.navigationController popViewControllerAnimated:YES];

    [timer invalidate];

    

#pragma mark -----在此处判断是否为toon内部使用的url--------

    if([stringValue hasPrefix:@"http://www.sqtoon.com/todownLoad.do?"])//判断如果为toon可识别的url

    {

        

        CardOwnerController *cardOwner = [[CardOwnerController alloc]init];

        cardOwner.type= 1;

        NSString *keyValueStr =  [stringValue substringFromIndex:36];

        NSLog(@"keyValueStr:%@",keyValueStr);

        NSArray *tempArr = [keyValueStr componentsSeparatedByString:@"&"];

        if([tempArr count] == 2)//说明为名片二维码

        {

            _cardId = [tempArr[1] substringFromIndex:7];

            NSLog(@"_cardId:%@",_cardId);

            cardOwner.friendCardId = [NSString stringWithFormat:@"%@",_cardId];

            [self.navigationController pushViewController:cardOwner animated:YES];

        }

        if([tempArr count] == 3)

        {

            ActivityInfoModel *model = [[ActivityInfoModel alloc]init];

            model.cardId = [tempArr[1] substringFromIndex:7];

            model.activityId = [tempArr[2] substringFromIndex:11];

            ActivityDetailViewController *detail = [[ActivityDetailViewController alloc]initWithActivityModel:model];

            [self.navigationController pushViewController:detail animated:YES];

        }

        

    }else //不是toon内部url

        

    {

        SweepResultViewController *sweepResult = [[SweepResultViewController alloc]init];

        sweepResult.urlStr = stringValue;

        [self.navigationController pushViewController:sweepResult animated:YES];


    }

   NSLog(@"stringValue:  %@",stringValue);

      

}



- (void)didReceiveMemoryWarning

{

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}


@end



核心就是上面限制扫描区域的一句话,哈哈,到此你就可以去运行了;

好多人说系统方法没有第三方库的扫描速度快,这里我必须说一下,亲测系统的方法扫描速度杠杠滴;尤其是不限制扫描区域的时候,限制了之后会有所下降,但依然是很灵敏的;不得不说苹果一出,必属精品。下面是运行效果图。。。。。。。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值