2019独角兽企业重金招聘Python工程师标准>>>
//需要真机
#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>@interface ViewController ()<AVCaptureMetadataOutputObjectsDelegate>//用于处理采集信息的代理
{AVCaptureSession * session;//输入输出的中间桥梁
}
@end
@implementation ViewController- (void)viewDidLoad {[super viewDidLoad];// Do any additional setup after loading the view, typically from a nib.//获取摄像设备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];// 1、这个CGRect参数和普通的Rect范围不太一样,它的四个值的范围都是0-1,表示比例。
// 2、经过测试发现,这个参数里面的x对应的恰恰是距离左上角的垂直距离,y对应的是距离左上角的水平距离。
// 3、宽度和高度设置的情况也是类似。
// 3、举个例子如果我们想让扫描的处理区域是屏幕的下半部分,我们这样设置
// output.rectOfInterest=CGRectMake(0.5,0,0.5, 1);[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];//开始捕获[session startRunning];
}#pragma mark 信息捕获代理方法
-(void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection{if (metadataObjects.count>0) {//[session stopRunning];AVMetadataMachineReadableCodeObject * metadataObject = [metadataObjects objectAtIndex : 0 ];//输出扫描字符串NSLog(@"%@",metadataObject.stringValue);}
}@end