//------------------------------------------------------
1.调用方式。
//------------------------------------------------------
ErWeiViewController *vc = [[ErWeiViewController alloc]init];
[vc setScanSuccessCallback:^(NSString *scanResult) {
NSLog(@"==scanResult=%@",scanResult);
[self performSelectorOnMainThread:@selector(afterScan:) withObject:scanResult waitUntilDone:YES];
}];
[self.navigationController pushViewController:vc animated:YES];
//------------------------------------------------------
h文件
//------------------------------------------------------
//
// ErWeiViewController.h
// wdsjd
//
// Created by apple on 15/11/17.
// Copyright © 2015年 Harrison. All rights reserved.
//
#import "CommonViewController.h"
#import <AVFoundation/AVFoundation.h>
typedef void(^ScanSuccessCallback)(NSString *scanResult);
@interface ErWeiViewController : UIViewController
{
CAGradientLayer *gradient;;
float kPadding;
float shadeHeight;
CGRect cropRect;
CALayer *blueLineLayer;
SystemSoundID beepSound;
ScanSuccessCallback scanSuccessCallback;
BOOL alreadyInvoke;
}
-(BOOL)startReading;
-(void)stopReading;
//捕捉会话
//@property (nonatomic, strong) AVCaptureSession *captureSession;
//展示layer
//@property (nonatomic, strong) AVCaptureVideoPreviewLayer *videoPreviewLayer;
@property(nonatomic, assign)BOOL isReading;
//@property (strong, nonatomic) UIView *boxView;
//@property (strong, nonatomic) CALayer *scanLayer;
@property (strong, nonatomic) UIView *viewPreview;
@property (strong, nonatomic) UILabel *lblStatus;
@property (strong, nonatomic) UIButton *startBtn;
@property (nonatomic, retain) NSURL *soundToPlay;
@property(nonatomic) BOOL isStatusBarHidden;
- (void)startStopReading:(id)sender;
-(void)setScanSuccessCallback:(ScanSuccessCallback)callback;
@end
//------------------------------------------------------
m文件
//------------------------------------------------------
//
// ErWeiViewController.m
// wdsjd
//
// Created by apple on 15/11/17.
// Copyright © 2015年 Harrison. All rights reserved.
//
#import "ErWeiViewController.h"
#define BLUE_COLOR [UIColor colorWithRed:51/255.0 green:161/255.0 blue:201/255.0 alpha:1]
#if !TARGET_IPHONE_SIMULATOR
#define HAS_AVFF 1
#endif
@interface ErWeiViewController ()<AVCaptureMetadataOutputObjectsDelegate>//用于处理采集信息的代理
{
AVCaptureSession * session;//输入输出的中间桥梁
}
@end
@implementation ErWeiViewController
- (void)viewDidLoad {
[super viewDidLoad];
_isReading = NO;
alreadyInvoke =NO;
[self.navigationController setNavigationBarHidden:YES];
[self startReading];
NSBundle *mainBundle = [NSBundle mainBundle];
self.soundToPlay =
[NSURL fileURLWithPath:[mainBundle pathForResource:@"beep-beep" ofType:@"aiff"] isDirectory:NO];
beepSound = -1;
if (beepSound != (SystemSoundID)-1) {
AudioServicesPlaySystemSound(beepSound);
}
}
-(void)setScanSuccessCallback:(ScanSuccessCallback)callback
{
scanSuccessCallback = callback;
}
-(void)boxView
{
kPadding= 20 ;//(CGRectGetWidth(self.view.frame)-40)/2;
CGFloat scanWidth = self.view.frame.size.width - kPadding * 2;
float scanHeight = 150;
cropRect = CGRectMake(kPadding, (self.view.frame.size.height - scanHeight) / 2, scanWidth, scanHeight);
UIScreen *screen = [UIScreen mainScreen];
float w = CGRectGetWidth(screen.bounds);
float screenW =w;
float maxX= CGRectGetMaxX(cropRect);
float minY= CGRectGetMinY(cropRect);
float maxY =CGRectGetMaxY(cropRect);
CGRect frame =CGRectMake(0, 0, screenW, minY);
UIView *row1= [self getAlphaColor:frame];
[_viewPreview addSubview:row1];
//--------
frame =CGRectMake(0, maxY, screenW, minY);
UIView *row2= [self getAlphaColor:frame];
[_viewPreview addSubview:row2];
//-------------
frame =CGRectMake(0, minY, kPadding, CGRectGetHeight(cropRect));
UIView *row3= [self getAlphaColor:frame];
[self.view addSubview:row3];
//-------------
frame =CGRectMake(maxX, minY, kPadding, CGRectGetHeight(cropRect));
UIView *row4= [self getAlphaColor:frame];
[_viewPreview addSubview:row4];
float lineH=3;
float len=15;
float lineX=kPadding-lineH;
float lineY=(CGRectGetMinY(cropRect)-lineH);
float verticalH=len-lineH;
//左上角
frame=CGRectMake(lineX, lineY, len, lineH);
CGRect shuFrame=CGRectMake(lineX, lineY+lineH, lineH, verticalH);
[self setZhiJiao:frame withShuFrame:shuFrame];
//左下角
lineY=(CGRectGetMaxY(cropRect));
frame=CGRectMake(lineX, lineY, len, lineH);
shuFrame=CGRectMake(lineX, lineY-(verticalH), lineH, verticalH);
[self setZhiJiao:frame withShuFrame:shuFrame];
//右上角
lineX=CGRectGetMaxX(cropRect)-verticalH;
lineY=(CGRectGetMinY(cropRect)-lineH);
frame=CGRectMake(lineX, lineY, len, lineH);
maxX=CGRectGetMaxX(cropRect);
shuFrame=CGRectMake(maxX, lineY+lineH, lineH, verticalH);
[self setZhiJiao:frame withShuFrame:shuFrame];
//右下角
lineX=CGRectGetMaxX(cropRect)-verticalH;
lineY=(CGRectGetMaxY(cropRect));
frame=CGRectMake(lineX, lineY, len, lineH);
maxX=CGRectGetMaxX(cropRect);
shuFrame=CGRectMake(maxX, lineY-verticalH, lineH, verticalH);
[self setZhiJiao:frame withShuFrame:shuFrame];
}
-(void) drawLinearGradient
{
float blueLineH=2;
if (gradient)
{
// [gradient removeFromSuperlayer];
shadeHeight+=7;
if (shadeHeight>=CGRectGetHeight(cropRect))
{
shadeHeight=0;
}
gradient.frame = CGRectMake(CGRectGetMinX(cropRect), CGRectGetMinY(cropRect), CGRectGetWidth(cropRect), shadeHeight);
gradient.colors = [NSArray arrayWithObjects:(id)[BLUE_COLOR colorWithAlphaComponent:0.2].CGColor,
(id)[BLUE_COLOR colorWithAlphaComponent:0.5].CGColor,
nil];
blueLineLayer.frame=CGRectMake(CGRectGetMinX(cropRect), CGRectGetMaxY(gradient.frame)-blueLineH, CGRectGetWidth(cropRect), blueLineH);
}else
{
shadeHeight =30;
gradient = [CAGradientLayer layer];
gradient.frame = CGRectMake(CGRectGetMinX(cropRect), CGRectGetMinY(cropRect), CGRectGetWidth(cropRect), shadeHeight);
gradient.colors = [NSArray arrayWithObjects:(id)[BLUE_COLOR colorWithAlphaComponent:0.0].CGColor,
(id)[BLUE_COLOR colorWithAlphaComponent:0.3].CGColor,
nil];
// gradient.backgroundColor = [[UIColor orangeColor] CGColor];
blueLineLayer=[CALayer layer];
blueLineLayer.frame=CGRectMake(CGRectGetMinX(cropRect), CGRectGetMaxY(gradient.frame)-blueLineH, CGRectGetWidth(cropRect), blueLineH);
blueLineLayer.backgroundColor=[BLUE_COLOR CGColor];
[self.viewPreview.layer insertSublayer:blueLineLayer above:gradient];
[self.viewPreview.layer insertSublayer:gradient below:blueLineLayer ];
}
}
-(UIView *)getAlphaColor:(CGRect)frame
{
UIView *v = [[UIView alloc]initWithFrame:frame];
UIColor *alphaColor = [[UIColor blackColor] colorWithAlphaComponent:0.8];
v.backgroundColor = alphaColor;
return v;
}
-(void)setZhiJiao:(CGRect)henFrame withShuFrame:(CGRect)shuFrame
{
[self.view addSubview:[self blueLine:henFrame]];
[self.view addSubview:[self blueLine:shuFrame]];
}
-(UIView *)blueLine:(CGRect)frame
{
UIView *line = [[UIView alloc]initWithFrame:frame];
line.backgroundColor=BLUE_COLOR;
return line;
}
-(BOOL)prefersStatusBarHidden
{
return NO;
}
-(BOOL)startReading {
_viewPreview = [[UIView alloc]initWithFrame:self.view.bounds];
[self.view addSubview:_viewPreview];
//获取摄像设备
AVCaptureDevice * device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
//创建输入流
AVCaptureDeviceInput * input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
//创建输出流
AVCaptureMetadataOutput * output = [[AVCaptureMetadataOutput alloc]init];
//设置代理 在主线程里刷新
[output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
//初始化链接对象
session = [[AVCaptureSession alloc]init];
//高质量采集率
[session setSessionPreset:AVCaptureSessionPresetHigh];
[session addInput:input];
[session addOutput:output];
//设置扫码支持的编码格式(如下设置条形码和二维码兼容)
output.metadataObjectTypes=@[AVMetadataObjectTypeQRCode,AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code];
AVCaptureVideoPreviewLayer * layer = [AVCaptureVideoPreviewLayer layerWithSession:session];
layer.videoGravity=AVLayerVideoGravityResizeAspectFill;
layer.frame=self.view.layer.bounds;
[self.view.layer insertSublayer:layer atIndex:0];
//9.将图层添加到预览view的图层上
[_viewPreview.layer addSublayer:layer];
//10.设置扫描范围
//layer.rectOfInterest = CGRectMake(0.2f, 0.2f, 0.8f, 0.8f);
// //10.1.扫描框
[self boxView];
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.1f target:self selector:@selector(moveScanLayer:) userInfo:nil repeats:YES];
[timer fire];
//10.开始扫描
//开始捕获
[session startRunning];
return YES;
}
//-(void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection{
// if (metadataObjects.count>0) {
// //[session stopRunning];
// AVMetadataMachineReadableCodeObject * metadataObject = [metadataObjects objectAtIndex : 0 ];
// //输出扫描字符串
// NSLog(@"%@",metadataObject.stringValue);
// }
//}
#pragma mark - AVCaptureMetadataOutputObjectsDelegate协议方法
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
//判断是否有数据
if (metadataObjects != nil && [metadataObjects count] > 0) {
AVMetadataMachineReadableCodeObject *metadataObj = [metadataObjects objectAtIndex:0];
//判断回传的数据类型 captureMetadataOutput.metadataObjectTypes 数组里的类型进行遍历对比 添加if判断类型,
// 下面只以AVMetadataObjectTypeQRCode 为例子
// if ([[metadataObj type] isEqualToString:AVMetadataObjectTypeQRCode]) {
NSLog(@"[metadataObj stringValue] == %@",[metadataObj stringValue]);
scanSuccessCallback([metadataObj stringValue]);
_isReading = NO;
[self performSelectorOnMainThread:@selector(stopReading) withObject:nil waitUntilDone:NO];
// }
}
[self dismissViewControllerAnimated:YES completion:^{
}];
}
//实现计时器方法moveScanLayer:(NSTimer *)timer
- (void)moveScanLayer:(NSTimer *)timer
{
[self drawLinearGradient];
// CGRect frame = _scanLayer.frame;
// if (_boxView.frame.size.height < _scanLayer.frame.origin.y) {
// frame.origin.y = 0;
// _scanLayer.frame = frame;
// }else{
// frame.origin.y += 5;
// [UIView animateWithDuration:0.1 animations:^{
// _scanLayer.frame = frame;
// }];
// }
}
-(void)stopReading{
if (!alreadyInvoke)
{
alreadyInvoke= YES;
[self.navigationController setNavigationBarHidden:NO];
[self clear];
[self.navigationController popViewControllerAnimated:YES];
}
}
-(void)clear
{
[self.viewPreview removeFromSuperview];
[session stopRunning];
session = nil;
// [_scanLayer removeFromSuperlayer];
// [_videoPreviewLayer removeFromSuperlayer];
}
//-------
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
self.isStatusBarHidden = [[UIApplication sharedApplication] isStatusBarHidden];
if (!self.isStatusBarHidden)
[[UIApplication sharedApplication] setStatusBarHidden:NO];
[self setTopPart];
}
- (void)viewDidDisappear:(BOOL)animated {
[super viewDidDisappear:animated];
if (!self.isStatusBarHidden)
[[UIApplication sharedApplication] setStatusBarHidden:NO];
}
-(void)toCancelEvent:(UIButton *)sender
{
NSLog(@"-----");
}
//--------
-(void)setTopPart
{
//返回和闪光灯
float x=0;
float y=0;
UIScreen *screen = [UIScreen mainScreen];
float w = CGRectGetWidth(screen.bounds);
// float screenHeight = CGRectGetHeight(screen.bounds);
float screenW =w;
float stateH =20;
float navHeight=44;
float h=stateH+navHeight;
CGRect frame =CGRectMake(x, y, w, h);
UIView *v = [[UIView alloc]initWithFrame:frame];
v.backgroundColor=[UIColor clearColor];//[UIColor colorWithRed:51.0/255.0 green:161.0/255.0 blue:201.0/255.0 alpha:1];
//-----返回---
UIButton *backButton =[[UIButton alloc]initWithFrame:CGRectMake(0, 0, 100, h)];
[backButton addTarget:self action:@selector(cancel:) forControlEvents:UIControlEventTouchUpInside];
[v addSubview:backButton];
w=31;
h=31;
y=(navHeight-h)/2+stateH;
x=20;
frame = CGRectMake(x, y, w, h);
UIImageView *backImgView = [[UIImageView alloc]initWithFrame:frame];
backImgView.image=[UIImage imageNamed:@"return_scan.png"];
[backButton addSubview:backImgView];
[v addSubview:backButton];
//标题
// w=120;
//
// x=(screenW-w)/2;
// y=stateH;
// h=navHeight;
//
// frame = CGRectMake(x, y, w, h);
// UILabel *titleLbl =[[UILabel alloc]initWithFrame:frame];
//
// titleLbl.font=[UIFont systemFontOfSize:18];
//
// titleLbl.textColor=[UIColor whiteColor];
//
//
// titleLbl.text=titleStr;
//
// titleLbl.textAlignment=NSTextAlignmentCenter;
//
// [v addSubview:titleLbl];
//闪光灯
//---------------
w=31;
x=(screenW-w)/2;
frame = CGRectMake(x, y, w, w);
UIButton *sanGuangDengBtn = [[UIButton alloc]initWithFrame:frame];
[sanGuangDengBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[sanGuangDengBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
sanGuangDengBtn.titleLabel.font=[UIFont systemFontOfSize:16];
[sanGuangDengBtn setBackgroundImage:[UIImage imageNamed:@"light_scan.png"] forState:UIControlStateNormal];
[sanGuangDengBtn setBackgroundImage:[UIImage imageNamed:@"selected_light_scan.png"] forState:UIControlStateSelected];
[sanGuangDengBtn addTarget:self action:@selector(openShanGuangDeng:) forControlEvents:UIControlEventTouchUpInside];
[v addSubview:sanGuangDengBtn];
[self.view addSubview:v];
}
-(void)cancel:(UIButton *)s
{
// [self cancelled];
[self stopReading];
// [self.navigationController popViewControllerAnimated:YES];
}
-(void)openShanGuangDeng:(UIButton *)s
{
if (s.selected)
{
s.selected=NO;
[self setTorch:NO];
}else
{
s.selected=YES;
[self setTorch:YES];
}
}
#pragma mark - Torch
- (void)setTorch:(BOOL)status {
#if HAS_AVFF
Class captureDeviceClass = NSClassFromString(@"AVCaptureDevice");
if (captureDeviceClass != nil) {
AVCaptureDevice *device = [captureDeviceClass defaultDeviceWithMediaType:AVMediaTypeVideo];
[device lockForConfiguration:nil];
if ( [device hasTorch] ) {
if ( status ) {
[device setTorchMode:AVCaptureTorchModeOn];
} else {
[device setTorchMode:AVCaptureTorchModeOff];
}
}
[device unlockForConfiguration];
}
#endif
}
-(void)cancelled
{
NSLog(@"---cancelled---");
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
self.wantsFullScreenLayout = YES;
if ([self soundToPlay] != nil) {
OSStatus error = AudioServicesCreateSystemSoundID((__bridge CFURLRef)[self soundToPlay], &beepSound);
if (error != kAudioServicesNoError) {
NSLog(@"Problem loading nearSound.caf");
}
}
}
- (void)dealloc {
if (beepSound != (SystemSoundID)-1) {
AudioServicesDisposeSystemSoundID(beepSound);
}
[self clear];
}
@end