系统方法实现仿微信、支付宝二维码扫描 实现 (限制扫描区域、相机背景)
2014-12-29 09:34
579 查看
.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
核心就是上面限制扫描区域的一句话,哈哈,到此你就可以去运行了;
好多人说系统方法没有第三方库的扫描速度快,这里我必须说一下,亲测系统的方法扫描速度杠杠滴;尤其是不限制扫描区域的时候,限制了之后会有所下降,但依然是很灵敏的;不得不说苹果一出,必属精品。下面是运行效果图。。。。。。。
//
// 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
核心就是上面限制扫描区域的一句话,哈哈,到此你就可以去运行了;
好多人说系统方法没有第三方库的扫描速度快,这里我必须说一下,亲测系统的方法扫描速度杠杠滴;尤其是不限制扫描区域的时候,限制了之后会有所下降,但依然是很灵敏的;不得不说苹果一出,必属精品。下面是运行效果图。。。。。。。
相关文章推荐
- iOS 系统二维码扫描(可限制扫描区域)
- iOS 原生二维码扫描(可限制扫描区域)
- iOS 原生二维码扫描(可限制扫描区域)
- ios开发原生的扫描二维码的实现以及限制扫描区域rectOfInterest遇到的一些坑
- 在微信、支付宝、百度钱包实现点击返回按钮关闭当前页面和窗口的方法
- 一个微信投票系统的投票限制实现
- JS实现点击颜色块切换指定区域背景颜色的方法
- 原生二维码扫描,可限制扫描区域,识别相册二维码
- Android使用系统方法实现分享到QQ和微信!
- 在微信、支付宝、百度钱包实现点击返回按钮关闭当前页面和窗口的方法
- [系统集成] RT(Request Tracker)执行自定义脚本及发送微信、短信的实现方法
- iOS 原生二维码扫描(可限制扫描区域)
- python端口扫描系统实现方法
- C#.NET 大型企业信息化系统集成快速开发平台 4.2 版本 - 访问频率限制功能实现、防止黑客扫描、防止恶意刷屏
- iOS 原生实现扫描二维码和条形码功能限制扫描区域
- Android 调用系统相机拍摄获取照片的两种方法实现实例
- iOS 原生二维码扫描(可限制扫描区域)
- iOS使用系统API扫描二维码条形码&限制扫描区域
- Android编程实现自定义系统菜单背景的方法
- 微信小程序图片选择区域裁剪实现方法