iOS开发(OC)——二维码扫描(原生API,支持条形码)

来源:互联网 发布:vb tooltiptext 换行 编辑:程序博客网 时间:2024/05/17 01:26

今天,我为大家介绍一下iOS原生API实现二维码和条形码扫描功能

在Github上,我已经写好了Demo,有兴趣的可以下载下来看看代码里有注释。网址:https://github.com/liumude/CodeScan

主要代码如下

//获取摄像设备    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.layer.bounds;    [self.layer insertSublayer:layer atIndex:0];    //开始捕获    [session startRunning];    //扫描的范围    output.rectOfInterest=CGRectMake(0,0,1.0, 1.0);
0 0