先上Demo地址
上效果图
该效果基于OC原生语言写出,下边步入正题
二维码,条形码扫描,肯定会用到相机,但是苹果说了,你用我相机要通知用户权限,不然不给用。所以,先添加plist相机权限
当前界面一个是用到系统原生类AVCaptureSession。创建会话,AVCaptureVideoPreviewLayer摄像头预览功能,当然还有一系列代理方法。中间挖空的视图同时存在一个线条动画。
首先我们要考虑一个问题,权限问题。如果用户自己点拒绝了,下次怎么搞。这里我在每次视图将要显示的时候做了一个处理
-(void)viewWillAppear:(BOOL)animated{
AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
switch (status) {
case AVAuthorizationStatusNotDetermined:{
// 许可对话没有出现,发起授权许可
[AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
dispatch_async(dispatch_get_main_queue(), ^{
if (granted) {
//第一次用户接受
}else{
//用户拒绝
[self ocrOnFail:@"用户拒绝授权,无法扫描"];
[self.navigationController popViewControllerAnimated:YES];
}
});
}];
break;
}
case AVAuthorizationStatusAuthorized:{
// 已经开启授权,可继续
break;
}
default:
break;
}
NSString * mediaType = AVMediaTypeVideo;// 媒体权限
AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];// 读取设备权限
if (authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied) {// 用户明确地拒绝授权,或者相机设备无法访问
self.noneCameraPermissionsBlock();
[self.navigationController popViewControllerAnimated:YES];
return;
}
if (!_captureSession.running)
{
[self startReading];
}
}
以上是权限问题解决。下边创建我们的会话,以及视图扫描工具
#import
#import
typedef void(^CKUniversityBlock)(NSString * contents);
typedef void(^CKNoPermissionsBlock)();
@interface NXZCodeViewController : UIViewController
{
//会话
AVCaptureSession *_captureSession;
//摄像头预览
AVCaptureVideoPreviewLayer *_videoPreviewLayer;
}
@property (nonatomic,assign)BOOL qrcodeFlag ;
@property (nonatomic,copy) CKUniversityBlock wenhuiUniversityConfirmBlock;
@property (nonatomic,copy) CKNoPermissionsBlock noneCameraPermissionsBlock;
@end
.m创建
- (BOOL)startReading {
NSError *error;
//硬件设备
AVCaptureDevice *captureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
//输入源
AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:captureDevice error:&error];
if (!input) {
return NO;
}
//会话
_captureSession = [[AVCaptureSession alloc] init];
//将输入源添加到会话里
[_captureSession addInput:input];
//输出源-元数据的output
AVCaptureMetadataOutput *captureMetadataOutput = [[AVCaptureMetadataOutput alloc] init];
//将输出添加到会话中
[_captureSession addOutput:captureMetadataOutput];
//创建队列
dispatch_queue_t dispatchQueue;
dispatchQueue = dispatch_queue_create("myQueue", NULL);
//给output设置代理,并添加队列
[captureMetadataOutput setMetadataObjectsDelegate:self queue:dispatchQueue];
captureMetadataOutput.rectOfInterest = CGRectMake(((SCREEN_HEIGHT-64) / 2 - 220 / 2 -40)/SCREEN_HEIGHT, (SCREEN_WIDTH / 2 - 220 / 2)/SCREEN_WIDTH, 220/SCREEN_HEIGHT, 220/SCREEN_WIDTH);
captureMetadataOutput.metadataObjectTypes = @[AVMetadataObjectTypeQRCode,AVMetadataObjectTypeEAN13Code,AVMetadataObjectTypeEAN8Code,AVMetadataObjectTypeCode128Code,AVMetadataObjectTypeInterleaved2of5Code,AVMetadataObjectTypeUPCECode];
//视频预览图层
_videoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:_captureSession];
[_videoPreviewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
[_videoPreviewLayer setFrame:self.view.layer.bounds];
[self.view.layer insertSublayer:_videoPreviewLayer atIndex:0];
[self configuredZBarReaderMaskView];
[_qrRectView startScan];
//开始运行会话
[_captureSession startRunning];
return YES;
}
别忘记设计代理回调奥,要不那不到我们要的扫描结果的
AVCaptureMetadataOutputObjectsDelegate
#pragma mark - AVCaptureMetadataOutputObjectsDelegate
-(void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects
fromConnection:(AVCaptureConnection *)connection
{
[_captureSession stopRunning];
[_qrRectView stopScan];
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"%@/n%@",metadataObjects,connection);
if (metadataObjects != nil && [metadataObjects count] > 0)
{
AVMetadataMachineReadableCodeObject *metadataObj = [metadataObjects objectAtIndex:0];
NSLog(@"%@",metadataObj.stringValue);
NSString *msgStr=metadataObj.stringValue;
//@"http://qr.bookln.cn/qr.html?crcode=110000000F00000000000000B3ZX1CEC"
[self ocrOnFail:msgStr];
}else{
[self ocrOnFail:@"扫描失败"];
[self.navigationController popViewControllerAnimated:YES];
return;
}
});
}
- (void)ocrOnFail:(NSString *)error {
NSLog(@"%@", error);
NSString *msg = [NSString stringWithFormat:@"%@", error];
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"识别信息" message:msg preferredStyle:UIAlertControllerStyleActionSheet];
UIAlertAction * action = [UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
[_captureSession startRunning];
[_qrRectView startScan];
}];
[alert addAction:action];
[self presentViewController:alert animated:YES completion:nil];
}];
[_captureSession stopRunning];
}
到此,当前视图的扫描基本就满足我们扫描二维码和条形码的需求了。但是中间镂空的动画视图呢?在那里。。。
别着急,我们下边创建中间镂空的视图,并添加动画效果
自定义一个View继承UIView
@interface QRView : UIView
/**
* 透明的区域
*/
@property (nonatomic, assign) CGSize transparentArea;
- (void)startScan;
- (void)stopScan;
@end
.m方法
创建线条图片,
if(!_line){
_line = [[UIImageView alloc] init];
_line.image = [UIImage imageNamed:@"QRCodeScanLine"];
[_line setBackgroundColor:[UIColor clearColor]];
_line.contentMode = UIViewContentModeScaleAspectFill;
[self addSubview:_line];
}
}
四个边添加,并且镂空,这里用到CGContextRef,不会的同学可自行百度,讲解很详细
- (void)addCornerLineWithContext:(CGContextRef)ctx rect:(CGRect)rect{
//画四个边角
CGContextSetLineWidth(ctx, 2);
CGContextSetRGBStrokeColor(ctx, 52 /255.0, 152/255.0, 219/255.0, 1);//蓝色
//左上角
CGPoint poinsTopLeftA[] = {
CGPointMake(rect.origin.x+0.7, rect.origin.y),
CGPointMake(rect.origin.x+0.7 , rect.origin.y + 15)
};
CGPoint poinsTopLeftB[] = {CGPointMake(rect.origin.x, rect.origin.y +0.7),CGPointMake(rect.origin.x + 15, rect.origin.y+0.7)};
[self addLine:poinsTopLeftA pointB:poinsTopLeftB ctx:ctx];
//左下角
CGPoint poinsBottomLeftA[] = {CGPointMake(rect.origin.x+ 0.7, rect.origin.y + rect.size.height - 15),CGPointMake(rect.origin.x +0.7,rect.origin.y + rect.size.height)};
CGPoint poinsBottomLeftB[] = {CGPointMake(rect.origin.x , rect.origin.y + rect.size.height - 0.7) ,CGPointMake(rect.origin.x+0.7 +15, rect.origin.y + rect.size.height - 0.7)};
[self addLine:poinsBottomLeftA pointB:poinsBottomLeftB ctx:ctx];
//右上角
CGPoint poinsTopRightA[] = {CGPointMake(rect.origin.x+ rect.size.width - 15, rect.origin.y+0.7),CGPointMake(rect.origin.x + rect.size.width,rect.origin.y +0.7 )};
CGPoint poinsTopRightB[] = {CGPointMake(rect.origin.x+ rect.size.width-0.7, rect.origin.y),CGPointMake(rect.origin.x + rect.size.width-0.7,rect.origin.y + 15 +0.7 )};
[self addLine:poinsTopRightA pointB:poinsTopRightB ctx:ctx];
CGPoint poinsBottomRightA[] = {CGPointMake(rect.origin.x+ rect.size.width -0.7 , rect.origin.y+rect.size.height+ -15),CGPointMake(rect.origin.x-0.7 + rect.size.width,rect.origin.y +rect.size.height )};
CGPoint poinsBottomRightB[] = {CGPointMake(rect.origin.x+ rect.size.width - 15 , rect.origin.y + rect.size.height-0.7),CGPointMake(rect.origin.x + rect.size.width,rect.origin.y + rect.size.height - 0.7 )};
[self addLine:poinsBottomRightA pointB:poinsBottomRightB ctx:ctx];
CGContextStrokePath(ctx);
}
- (void)addLine:(CGPoint[])pointA pointB:(CGPoint[])pointB ctx:(CGContextRef)ctx {
CGContextAddLines(ctx, pointA, 2);
CGContextAddLines(ctx, pointB, 2);
}
绘制
- (void)drawRect:(CGRect)rect {
//整个二维码扫描界面的颜色
CGSize viewSize =self.bounds.size;
CGRect screenDrawRect =CGRectMake(0, 0, viewSize.width,viewSize.height);
//中间清空的矩形框
CGRect clearDrawRect = CGRectMake(screenDrawRect.size.width / 2 - self.transparentArea.width / 2,
screenDrawRect.size.height / 2 - self.transparentArea.height / 2 -40,
self.transparentArea.width,self.transparentArea.height);
CGContextRef ctx = UIGraphicsGetCurrentContext();
[self addScreenFillRect:ctx rect:screenDrawRect];
[self addCenterClearRect:ctx rect:clearDrawRect];
[self addWhiteRect:ctx rect:clearDrawRect];
[self addCornerLineWithContext:ctx rect:clearDrawRect];
}
当然了,我们调用这个镂空框是要一句话调用开启动画,一句话调用结束动画的,所以我们开出两个方法
- (void)startScan;
- (void)stopScan;
.m实现
- (void)startScan{
if(_line){
isStop = NO;
if(nil == _line.superview){
[self addSubview:_line];
}
[self startAnimation];
}
}
- (void)stopScan{
isStop = YES;
[_line removeFromSuperview];
}
调用很方便的,
/**
*自定义扫描二维码视图样式
*@param 初始化扫描二维码视图的子控件
*/
- (void)configuredZBarReaderMaskView{
//扫描的矩形方框视图
_qrRectView = [[QRView alloc] init];
_qrRectView.transparentArea = CGSizeMake(220, 220);
_qrRectView.backgroundColor = [[UIColor blackColor]colorWithAlphaComponent:0.7];
[self.view addSubview:_qrRectView];
[_qrRectView mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.equalTo(self.view).with.offset(0);
make.left.equalTo(self.view).with.offset(0);
make.right.equalTo(self.view).with.offset(0);
make.bottom.equalTo(self.view).with.offset(0);
}];
self.topDetailLabel.hidden = NO;
self.topDetailLabel.text = @"请将二维码/条形码放入框中即可自动扫描";
self.topDetailLabel.center = CGPointMake(SCREEN_WIDTH/2, 100*OffHeight);
self.topDetailLabel.bounds = CGRectMake(0, 0, SCREEN_WIDTH, 10*OffHeight);
[_qrRectView addSubview:self.topDetailLabel];
//照明按钮
_lightingBtn = [UIButton buttonWithType:UIButtonTypeCustom];
[_lightingBtn setTitle:@"打开照明" forState:UIControlStateNormal];
[_lightingBtn setImage:[UIImage imageNamed:@"CJKTLightingImage"] forState:UIControlStateNormal];
[_lightingBtn.titleLabel setFont:[UIFont systemFontOfSize:10]];
[_lightingBtn setImageEdgeInsets:UIEdgeInsetsMake(0, 0, -20, 0)];
[_lightingBtn setTitleEdgeInsets:UIEdgeInsetsMake(93, -50, 0, 0)];
[_lightingBtn setTitleColor:[UIColor uiColorFromString:@"#c2c2c2"] forState:UIControlStateNormal];
[_lightingBtn setBackgroundColor:[UIColor clearColor]];
_lightingBtn.tag = LIGHTBUTTONTAG;
captureIs_Select = NO;
[_lightingBtn addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
[_qrRectView addSubview:_lightingBtn];
[_lightingBtn mas_makeConstraints:^(MASConstraintMaker *make) {
make.bottom.equalTo(_qrRectView).with.offset(-100*OffHeight);
make.centerX.equalTo(_qrRectView);
make.size.mas_equalTo(CGSizeMake(50, 70));
}];
}
这个代码量有点多,考虑封装性,大家有需要可以自己将view代码挪出去即可。
也可根据自己需求来私人定制属于自己的扫描软件奥。
Demo地址