今天在review代码的时候重新整理了一下项目中的原生的二维码扫描及生成的代码,和大家分享一下。
跟大家分享的主要有两个类:
QRCodeScanView 扫描视图, 识别出信息后回有震动提示,可以打开手电筒
QRCodeCreateTools 二维码、条形码生成工具,你还可以生成中间带小图标的二维码
先看看怎么使用吧
- (void)viewDidLoad {
[super viewDidLoad];
//创建扫面视图你只需要
self.scanView = [[QRCodeScanView alloc] initWithFrame:[UIScreen mainScreen].bounds minX:0.2 minY:0.2];
[self.view insertSubview:self.scanView atIndex:0];
}
效果图:
生成一个二维码
UIImage *qrcode = [QRCodeCreateTools creatQRCodeWithUrlstring:@"这是一个二维码" imageWidth:200];
生成一个中间带小图标的二维码
UIImage *iconQrcode = [QRCodeCreateTools creatQRCodeWithUrlstring:@"这是一个带头像的二维码" imageWidth:200 withIcon:icon withScale:0.2];
效果图:
生成一个条形码
UIImage *qrcode = [QRCodeCreateTools creatBarCode:@"11234598765" width:300 height:100];
有没有 很简单! 源码来了
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
@interface QRCodeScanView : UIView
@property (nonatomic, strong)UILabel *detailLabel;
@property (nonatomic, strong)UILabel *descriptionLabel;
@property (nonatomic, copy)void (^scanFinishBlock)(AVCaptureOutput *captureOutput, NSArray *metadataObjects, AVCaptureConnection *connection);
/**
* 初始化扫描视图
*
* @param frame 扫描视图的frame
* @param minX 扫描区域距视图左边界的比例
* @param minY 扫描区域距视图上边界的比例
*/
- (instancetype)initWithFrame:(CGRect)frame minX:(CGFloat)minX minY:(CGFloat)minY;
/**
* 开始扫描
*/
- (void)startScan;
/**
* 暂停扫描
*/
- (void)stopScan;
@end
#import "QRCodeScanView.h"
#import <AudioToolbox/AudioToolbox.h>
//扫描框四个角的颜色
#define BordColor [UIColor redColor]
//扫描线的颜色
#define ScanLineColor [UIColor redColor]
@interface QRCodeScanView ()<AVCaptureMetadataOutputObjectsDelegate, UIAlertViewDelegate>
{
NSTimer *_timer;
CGFloat _minX;
CGFloat _minY;
}
@property (nonatomic, strong)AVCaptureSession *session;
@property (nonatomic, strong)AVCaptureDeviceInput *input;
@property (nonatomic, strong)AVCaptureMetadataOutput *output;
@property (nonatomic, strong)AVCaptureVideoPreviewLayer *scanView;
@property (nonatomic, strong)UIImageView *scanLine;
@property (nonatomic, strong)UIView *boxView;
@end
@implementation QRCodeScanView
- (void)awakeFromNib
{
[super awakeFromNib];
_minX = 0.2;
_minY = 0.2;
[self setupUIWithMinX:0.2 minY:0.2];
}
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self != nil) {
_minX = 0.2;
_minY = 0.2;
[self setupUIWithMinX:0.2 minY:0.2];
}
return self;
}
- (instancetype)initWithFrame:(CGRect)frame minX:(CGFloat)minX minY:(CGFloat)minY
{
self = [super initWithFrame:frame];