2017年6月4日
一.原生实现二维码扫描功能
效果
1.实现
// HuScanViewController.h
#import
@interface HuScanViewController : UIViewController
// 扫描结果
@property (nonatomic, copy) void (^returnScanBarCodeValue)(NSString * barCodeString);
@end
// HuScanViewController.m
#import "HuScanViewController.h"
#import
#define SCREEN_WIDTH [UIScreen mainScreen].bounds.size.width
#define SCREEN_HEIGHT [UIScreen mainScreen].bounds.size.height
#define TOP (SCREEN_HEIGHT-220)/2
#define LEFT (SCREEN_WIDTH-220)/2
#define kScanRect CGRectMake(LEFT, TOP, 220, 220)
@interface ZFScanViewController ()
{
int num;
BOOL upOrdown;
NSTimer * timer;
CAShapeLayer *cropLayer;
}
/** 输入输出的中间桥梁 */
@property (strong,nonatomic)AVCaptureSession *session;
@property (strong,nonatomic)AVCaptureDevice *device;
@property (strong,nonatomic)AVCaptureDeviceInput *input;
@property (strong,nonatomic)AVCaptureMetadataOutput *output;
@property (strong,nonatomic)AVCaptureVideoPreviewLayer *preview;
/** 扫描支持的编码格式的数组 */
@property (nonatomic, strong) NSMutableArray * metadataObjectTypes;
@property (nonatomic, strong) UIImageView * line;
/** 取消按钮 */
@property (nonatomic, strong) UIButton * cancelButton;
@end
@implementation HuScanViewController
- (NSMutableArray *)metadataObjectTypes{
if (!_metadataObjectTypes) {
_metadataObjectTypes = [NSMutableArray arrayWithObjects:AVMetadataObjectTypeAztecCode, AVMetadataObjectTypeCode128Code, AVMetadataObjectTypeCode39Code, AVMetadataObjectTypeCode39Mod43Code, AVMetadataObjectTypeCode93Code, AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypePDF417Code, AVMetadataObjectTypeQRCode, AVMetadataObjectTypeUPCECode, nil];
// >= iOS 8
if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_7_1) {
[_metadataObjectTypes addObjectsFromArray:@[AVMetadataObjectTypeInterleaved2of5Code, AVMetadataObjectTypeITF14Code, AVMetadataObjectTypeDataMatrixCode]];
}
}
return _metadataObjectTypes;
}
- (void)viewWillDisappear:(BOOL)animated{
[super viewWillDisappear:animated];
}
- (void)viewDidLoad {
[super viewDidLoad];
[self configView];
[self initViewTitle:@"扫描条形码"];
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[self setCropRect:kScanRect];
[self performSelector:@selector(setupCamera) withObject:nil afterDelay:0.3];
}
// 添加遮罩层
- (void)configView{
UIImageView * imageView = [[UIImageView alloc]initWithFrame:kScanRect];
imageView.image = [UIImage imageNamed:@"pick_bg"];
[self.view addSubview:imageView];
upOrdown = NO;
num =0;
_line = [[UIImageView alloc] initWithFrame:CGRectMake(LEFT, TOP+10, 220, 2)];
_line.image = [UIImage imageNamed:@"line.png"];
[self.view addSubview:_line];
timer = [NSTimer scheduledTimerWithTimeInterval:.02 target:self selector:@selector(lineAnimation) userInfo:nil repeats:YES];
//取消按钮
CGFloat cancel_width = 100;
CGFloat cancel_height = 35;
CGFloat cancel_xPos = (SCREEN_WIDTH - cancel_width) / 2;
CGFloat cancel_yPos = SCREEN_HEIGHT - cancel_height - 3;
self.cancelButton = [UIButton buttonWithType:UIButtonTypeSystem];
self.cancelButton.frame = CGRectMake(cancel_xPos, cancel_yPos, cancel_width, cancel_height);
[self.cancelButton setTitle:@"取消" forState:UIControlStateNormal];
[self.cancelButton setTintColor:[UIColor whiteColor]];
[self.cancelButton addTarget:self action:@selector(cancelAction) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:self.cancelButton];
}
- (void)lineAnimation
{
if (upOrdown == NO) {
num ++;
_line.frame = CGRectMake(LEFT, TOP+10+2*num, 220, 2);
if (2*num == 200) {
upOrdown = YES;
}
}
else {
num --;
_line.frame = CGRectMake(LEFT, TOP+10+2*num, 220, 2);
if (num == 0) {
upOrdown = NO;
}
}
}
- (void)setCropRect:(CGRect)cropRect{
cropLayer = [[CAShapeLayer alloc] init];
CGMutablePathRef path = CGPathCreateMutable();
CGPathAddRect(path, nil, cropRect);
CGPathAddRect(path, nil, self.view.bounds);
[cropLayer setFillRule:kCAFillRuleEvenOdd];
[cropLayer setPath:path];
[cropLayer setFillColor:[UIColor blackColor].CGColor];
[cropLayer setOpacity:0.6];
[cropLayer setNeedsDisplay];
[self.view.layer addSublayer:cropLayer];
}
// 扫描初始化
- (void)setupCamera{
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
if (device==nil) {
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"设备没有摄像头" preferredStyle:UIAlertControllerStyleAlert];
[alert addAction:[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
}]];
[self presentViewController:alert animated:YES completion:nil];
return;
}
// 获取摄像设备Device
_device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
// 创建输入流Input
_input = [AVCaptureDeviceInput deviceInputWithDevice:self.device error:nil];
// 创建输出流Output(设置代理 在主线程里刷新)
_output = [[AVCaptureMetadataOutput alloc]init];
[_output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
//设置扫描区域
CGFloat top = TOP/SCREEN_HEIGHT;
CGFloat left = LEFT/SCREEN_WIDTH;
CGFloat width = 220/SCREEN_WIDTH;
CGFloat height = 220/SCREEN_HEIGHT;
///top 与 left 互换 width 与 height 互换
[_output setRectOfInterest:CGRectMake(top,left, height, width)];
//初始化链接对象
// Session
_session = [[AVCaptureSession alloc]init];
[_session setSessionPreset:AVCaptureSessionPresetHigh];
if ([_session canAddInput:self.input])
{
[_session addInput:self.input];
}
if ([_session canAddOutput:self.output])
{
[_session addOutput:self.output];
}
//设置扫描支持的编码格式(如下设置条形码和二维码兼容)
_output.metadataObjectTypes = self.metadataObjectTypes;
_preview =[AVCaptureVideoPreviewLayer layerWithSession:_session];
_preview.videoGravity = AVLayerVideoGravityResizeAspectFill;
_preview.frame =self.view.layer.bounds;
[self.view.layer insertSublayer:_preview atIndex:0];
//开始捕获
[_session startRunning];
}
#pragma mark - AVCaptureMetadataOutputObjectsDelegate
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection{
if (metadataObjects.count > 0) {
[_session stopRunning];
[timer setFireDate:[NSDate distantFuture]];
AVMetadataMachineReadableCodeObject * metadataObject = metadataObjects.firstObject;
self.returnScanBarCodeValue(metadataObject.stringValue);
if (self.navigationController) {
[self.navigationController popViewControllerAnimated:YES];
}else{
[self dismissViewControllerAnimated:YES completion:nil];
}
}
}
#pragma mark - 取消事件
// 取消事件
- (void)cancelAction{
if (self.navigationController) {
[self.navigationController popViewControllerAnimated:YES];
}else{
[self dismissViewControllerAnimated:YES completion:nil];
}
}
@end
2.使用
- (void)showScanView:(UIButton *)button
{
__weak typeof(self) weakself = self;
HuScanViewController * vc = [[HuScanViewController alloc] init];
vc.returnScanBarCodeValue = ^(NSString * barCodeString){
weakself.expressView.textField.text = barCodeString;
};
self.hidesBottomBarWhenPushed = YES;
[self.navigationController pushViewController:vc animated:YES];
}
如果您发现本文对你有所帮助,如果您认为其他人也可能受益,请把它分享出去。