
我们接下来将用maskLayer的方法,用最少的代码去绘制一个完整的二维码扫描UI界面
UIView *maskView = [[UIView alloc] initWithFrame:self.view.bounds];
maskView.backgroundColor = [UIColor colorWithRed:100/255.0 green:100/255.0 blue:100/255.0 alpha:0.4];
[self.view addSubview:maskView];
//创建mask layer
CAShapeLayer *maskLayer = [CAShapeLayer layer];
CGMutablePathRef path = CGPathCreateMutable();
CGFloat pathWidth = Width-100;
CGFloat orginY = (Height-pathWidth)/2-50;
//内部方框path
CGPathAddRect(path, nil, CGRectMake(50, orginY, pathWidth, pathWidth));
//外部大框path
CGPathAddRect(path, nil, maskView.bounds);
//两个path取差集,即去除差集部分
maskLayer.fillRule = kCAFillRuleEvenOdd;
maskLayer.path = path;
maskView.layer.mask = maskLayer;
这样我们便创建出我们需要的中部镂空,旁边灰色半透明的UI界面
添加环境光感应功能
在光线暗的时候提示打开手电筒
#import <AVFoundation/AVFoundation.h>
#import <ImageIO/ImageIO.h>
- (void)initScan {
//获取摄像设备
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
//创建输入流
AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
//创建输出流
AVCaptureMetadataOutput *output = [[AVCaptureMetadataOutput alloc] init];
//设置扫描有效区域
output.rectOfInterest = CGRectMake(0.1, 0.2, 0.5, 0.5);
//设置代理 在主线程里刷新
[output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
//设置光感代理输出
AVCaptureVideoDataOutput *respondOutput = [[AVCaptureVideoDataOutput alloc] init];
[respondOutput setSampleBufferDelegate:self queue:dispatch_get_main_queue()];
//初始化链接对象
_session = [[AVCaptureSession alloc] init];
//高质量采集率
[_session setSessionPreset:AVCaptureSessionPresetHigh];
if ([_session canAddInput:input]) [_session addInput:input];
if ([_session canAddOutput:output]) [_session addOutput:output];
if ([_session canAddOutput:respondOutput]) [_session addOutput:respondOutput];
//设置扫码支持的编码格式
output.metadataObjectTypes = @[AVMetadataObjectTypeQRCode, AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code];
_layer = [AVCaptureVideoPreviewLayer layerWithSession:_session];
_layer.videoGravity = AVLayerVideoGravityResizeAspectFill;
_layer.frame = self.view.frame;
[self.view.layer insertSublayer:_layer atIndex:0];
//开始捕获
[_session startRunning];
}
#pragma mark - 光感回调
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection {
CFDictionaryRef metadataDict = CMCopyDictionaryOfAttachments(NULL,sampleBuffer, kCMAttachmentMode_ShouldPropagate);
NSDictionary *metadata = [[NSMutableDictionary alloc] initWithDictionary:(__bridge NSDictionary*)metadataDict];
CFRelease(metadataDict);
NSDictionary *exifMetadata = [[metadata objectForKey:(NSString *)kCGImagePropertyExifDictionary] mutableCopy];
// 该值在 -5~12 之间,值越大光线越强
float brightnessValue = [[exifMetadata objectForKey:(NSString *)kCGImagePropertyExifBrightnessValue] floatValue];
NSLog(@"%f", brightnessValue);
}

接下来添加功能的UI界面就不做赘述,如有需要,Demo点这里
网友评论