iOS 使用系统扫码,自定义扫码界面

现在扫码功能的实现大概分两种:一种采用第三方ZXing、ZBar等来实现,另一种则是用系统自带的原生扫码实现。网上很多人说第三方实现的扫描效率低于原生扫描。到底是不是他们说的这样,我也没做过验证,就不做过多评论,但是我个人比较支持使用系统自带的原生扫码。
上代码:

@property (nonatomic, strong) AVCaptureDevice *captureDevice;
@property (nonatomic, strong) AVCaptureDeviceInput *captureDeviceInput;
@property (nonatomic, strong) AVCaptureMetadataOutput *captureMetadataOutput;
@property (nonatomic, strong) AVCaptureVideoPreviewLayer *captureVideoPreviewLayer;

- (void)setupScanner {
    //获取摄像设备
    _captureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    //创建输入流
    _captureDeviceInput = [AVCaptureDeviceInput deviceInputWithDevice:_captureDevice error:nil];
    //创建输出流
    _captureMetadataOutput = [[AVCaptureMetadataOutput alloc]init];
    //设置代理 在主线程里刷新
    [_captureMetadataOutput setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    //初始化链接对象
    _captureSession = [[AVCaptureSession alloc]init];
    //高质量采集率
    [_captureSession setSessionPreset:AVCaptureSessionPresetHigh];
    //添加输入、输出流
    if ([_captureSession canAddInput:self.captureDeviceInput]) {
        [_captureSession addInput:self.captureDeviceInput];
    }
    if ([_captureSession canAddOutput:self.captureMetadataOutput]) {
        [_captureSession addOutput:self.captureMetadataOutput];
    }
    //设置扫码支持的编码格式(如下设置条形码和二维码兼容)
    _captureMetadataOutput.metadataObjectTypes=@[AVMetadataObjectTypeQRCode,AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code];
    //设置扫描背景
    AVCaptureVideoPreviewLayer *previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:_captureSession];
    previewLayer.videoGravity=AVLayerVideoGravityResize;
    previewLayer.frame=self.view.layer.bounds;
    [self.view.layer insertSublayer:previewLayer atIndex:0];
    
    //修正扫描区域
    CGSize screenSize =[UIScreen mainScreen].bounds.size;
    CGRect cropRect = CGRectMake(screenSize.width*0.5-_QRCodeScannerView.scanAreaSize.width*0.5,
                                 80,
                                 _QRCodeScannerView.scanAreaSize.width,
                                 _QRCodeScannerView.scanAreaSize.height);
    _captureMetadataOutput.rectOfInterest = CGRectMake(cropRect.origin.y / screenSize.height,
                                                       cropRect.origin.x / screenSize.width,
                                                       cropRect.size.height / screenSize.height,
                                                       cropRect.size.width / screenSize.width);
}

_captureMetadataOutput.rectOfInterest  这个属性注意需要的是比例

iOS 使用系统扫码,自定义扫码界面_第1张图片
屏幕快照 2017-01-13 下午3.25.42.png

看上面张图片,怎样在一个蒙板上抠出扫描区域,

你可能感兴趣的:(iOS 使用系统扫码,自定义扫码界面)