h文件里
需要引入
#import <AVFoundation/AVFoundation.h>
#import <CoreImage/CoreImage.h>
签订协议
<AVCaptureMetadataOutputObjectsDelegate>
-(BOOL)startReading;
-(void)stopReading;
@property (retain,nonatomic) IBOutletUILabel *capLabel;
@property(strong,nonatomic)AVCaptureSession *captureSession;
@property(strong,nonatomic)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;
-(void)statStopReading:(id)sender;
@property(strong,nonatomic)UIImageView *ImageVIew;
m文件里
- (void)viewDidLoad {
[superviewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[superviewDidLoad];
_captureSession =nil;
_isReading = NO;
[selfstartReading];
}
#pragma mark 读取二维码
-(BOOL)startReading{
_viewPreview = [[UIViewalloc]initWithFrame:self.view.bounds];
[self.viewaddSubview:_viewPreview];
NSError *error;
//1.初始化捕捉设备(AVCaptureDevice),类型为AVMediaTypeVideo
AVCaptureDevice *captureDevice = [AVCaptureDevicedefaultDeviceWithMediaType:AVMediaTypeVideo];
//2.用captureDevice创建输入流
AVCaptureDeviceInput *input = [AVCaptureDeviceInputdeviceInputWithDevice:captureDevice error:&error];
if (!input) {
NSLog(@"%@", [errorlocalizedDescription]);
return NO;
}
//3.创建媒体数据输出流
AVCaptureMetadataOutput *captureMetadataOutput = [[AVCaptureMetadataOutputalloc] init];
//4.实例化捕捉会话
_captureSession = [[AVCaptureSessionalloc] init];
//4.1.将输入流添加到会话
[_captureSessionaddInput:input];
//4.2.将媒体输出流添加到会话中
[_captureSessionaddOutput:captureMetadataOutput];
//5.创建串行队列,并加媒体输出流添加到队列当中
dispatch_queue_t dispatchQueue;
dispatchQueue =dispatch_queue_create("myQueue",NULL);
//5.1.设置代理
[captureMetadataOutputsetMetadataObjectsDelegate:selfqueue:dispatchQueue];
//5.2.设置输出媒体数据类型为所有类型
captureMetadataOutput.metadataObjectTypes=@[AVMetadataObjectTypeQRCode,AVMetadataObjectTypeEAN13Code,AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code];
//6.实例化预览图层
_videoPreviewLayer = [[AVCaptureVideoPreviewLayeralloc] initWithSession:_captureSession];
//7.设置预览图层填充方式
[_videoPreviewLayersetVideoGravity:AVLayerVideoGravityResizeAspectFill];
//8.设置图层的frame
[_videoPreviewLayersetFrame:_viewPreview.layer.bounds];
//9.将图层添加到预览view的图层上
[_viewPreview.layeraddSublayer:_videoPreviewLayer];
//10.设置扫描范围
captureMetadataOutput.rectOfInterest =CGRectMake(0.2f,0.2f, 0.8f,0.8f);
//10.1.扫描框
_boxView = [[UIViewalloc] initWithFrame:CGRectMake(_viewPreview.bounds.size.width * 0.2f, _viewPreview.bounds.size.height *0.2f, _viewPreview.bounds.size.width -_viewPreview.bounds.size.width *0.4f, _viewPreview.bounds.size.height -_viewPreview.bounds.size.height *0.4f)];
_boxView.layer.borderColor = [UIColorgreenColor].CGColor;
_boxView.layer.borderWidth =1.0f;
[_viewPreview addSubview:_boxView];
//10.2.扫描线
_scanLayer = [[CALayeralloc] init];
_scanLayer.frame =CGRectMake(0,0, _boxView.bounds.size.width,1);
_scanLayer.backgroundColor = [UIColorbrownColor].CGColor;
[_boxView.layeraddSublayer:_scanLayer];
NSTimer *timer = [NSTimerscheduledTimerWithTimeInterval:0.2ftarget:selfselector:@selector(moveScanLayer:)userInfo:nilrepeats:YES];
[timerfire];
//10.4 上加上黑背景
UIView *backView1 = [[UIView alloc]initWithFrame:CGRectMake(0, 0, YQScreenW, YQScreenH * 0.3)];
backView1.backgroundColor = [UIColor blackColor];
backView1.alpha = 0.5;
[_viewPreview addSubview:backView1];
//10.5 加返回按钮
UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
backButton.frame = CGRectMake(20, 30, 40, 40);
[backButton addTarget:self action:@selector(actionBackButton:) forControlEvents:UIControlEventTouchUpInside ];
[backButton setTitle:@"返回" forState:UIControlStateNormal];
[backView1 addSubview:backButton];
//10.5.2 加label
UILabel *scanLable = [[UILabel alloc] initWithFrame:CGRectMake(YQScreenW/2 - 100, YQScreenH*0.3f - 50, 200, 30)];
scanLable.text = @"条形码~快递单~二维码";
scanLable.textColor = [UIColor whiteColor];
scanLable.textAlignment = NSTextAlignmentCenter;
[backView1 addSubview:scanLable];
//10.6 下加上黑背景
UIView *backView2 = [[UIView alloc]initWithFrame:CGRectMake(0, YQScreenH * 0.7, YQScreenW, YQScreenH * 0.3)];
backView2.backgroundColor = [UIColor blackColor];
backView2.alpha = 0.5;
[_viewPreview addSubview:backView2];
//11.开始扫描
[_captureSessionstartRunning];
return YES;
}
#pragma mark - AVCaptureMetadataOutputObjectsDelegate协议方法
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
//判断是否有数据
if (metadataObjects != nil && [metadataObjects count] > 0) {
AVMetadataMachineReadableCodeObject *metadataObj = [metadataObjectsobjectAtIndex:0];
//判断回传的数据类型 captureMetadataOutput.metadataObjectTypes 数组里的类型进行遍历对比 添加if判断类型,
// 下面只以AVMetadataObjectTypeQRCode 为例子
if ([[metadataObj type] isEqualToString:AVMetadataObjectTypeQRCode]) {
[_lblStatusperformSelectorOnMainThread:@selector(setText:)withObject:[metadataObj stringValue]waitUntilDone:NO];
NSLog(@"11111 = %@",_lblStatus.text);
[selfperformSelectorOnMainThread:@selector(stopReading)withObject:nilwaitUntilDone:NO];
_isReading = NO;
}
NSLog(@"2222 =%@", metadataObj.stringValue);
}
[selfdismissViewControllerAnimated:YEScompletion:^{
}];
}
//实现计时器方法moveScanLayer:(NSTimer *)timer
- (void)moveScanLayer:(NSTimer *)timer
{
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;
[UIViewanimateWithDuration:0.1animations:^{
_scanLayer.frame = frame;
}];
}
}
- (void)startStopReading:(id)sender {
if (!_isReading) {
if ([self startReading]) {
[_startBtnsetTitle:@"Stop"forState:UIControlStateNormal];
[_lblStatussetText:@"Scanning for QR Code"];
}
}
else{
[selfstopReading];
[_startBtnsetTitle:@"Start!"forState:UIControlStateNormal];
}
_isReading = !_isReading;
}
-(void)stopReading{
[_captureSessionstopRunning];
_captureSession =nil;
[_scanLayerremoveFromSuperlayer];
[_videoPreviewLayerremoveFromSuperlayer];
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
// 1.实例化二维码滤镜
CIFilter *filter = [CIFilterfilterWithName:@"CIQRCodeGenerator"];
// 2.恢复滤镜的默认属性 (因为滤镜有可能保存上一次的属性)
[filtersetDefaults];
// 3.将字符串转换成NSdata
NSData *data = [@"123456789123456789"dataUsingEncoding:NSUTF8StringEncoding];
// 4.通过KVO设置滤镜,传入data, 将来滤镜就知道要通过传入的数据生成二维码
[filtersetValue:data forKey:@"inputMessage"];
// 5.生成二维码
CIImage *outputImage = [filter outputImage];
UIImage *image = [UIImage imageWithCIImage:outputImage];
self.ImageVIew = [[UIImageViewalloc] initWithFrame:CGRectMake(100,200, 100, 100)];
[self.viewaddSubview:self.ImageVIew];
self.ImageVIew.image = image;
}