iOS开发生成二维码与扫描二维码

生成二维码:

.h文件

#import@interface NPDFgenerationOfQRCode : NSObject

- (UIImage *)buildQRcodeForString:(NSString *)qrCodeString accordingSize:(CGFloat)size;

@end

.m文件

#import "NPDFgenerationOfQRCode.h"#import@implementation NPDFgenerationOfQRCode

-(instancetype)init

{

self = [super init];

if (self) {

}

return self;

}

- (UIImage *)buildQRcodeForString:(NSString *)qrCodeString accordingSize:(CGFloat)size{

UIImage *codeImage = [self createNonInterpolatedUIImageFormCIImage:[self createQRCodeForString:qrCodeString] withSize:size];

return codeImage;

}

- (CIImage *)createQRCodeForString:(NSString *)qrCodeString

{

//创建二维码需要保存的数据

NSData *stringData = [qrCodeString dataUsingEncoding:NSUTF8StringEncoding];

// 创建filter

CIFilter *qrFilter = [CIFilter filterWithName:@"CIQRCodeGenerator"];

//清空滤镜

[qrFilter setDefaults];

// 设置内容和纠错级别

[qrFilter setValue:stringData forKey:@"inputMessage"];

[qrFilter setValue:@"H" forKey:@"inputCorrectionLevel"];

// 返回CIImage

return qrFilter.outputImage;

}

- (UIImage *)createNonInterpolatedUIImageFormCIImage:(CIImage *)image withSize:(CGFloat) size {

CGRect extent = CGRectIntegral(image.extent);

CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));

// 创建bitmap;

size_t width = CGRectGetWidth(extent) * scale;

size_t height = CGRectGetHeight(extent) * scale;

CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();

CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);

CIContext *context = [CIContext contextWithOptions:nil];

CGImageRef bitmapImage = [context createCGImage:image fromRect:extent];

CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);

CGContextScaleCTM(bitmapRef, scale, scale);

CGContextDrawImage(bitmapRef, extent, bitmapImage);

// 保存bitmap到图片

CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);

CGContextRelease(bitmapRef);

CGImageRelease(bitmapImage);

return [UIImage imageWithCGImage:scaledImage];

}

@end

扫描二维码:

.h文件

#import "DFBaseViewController.h"

typedef NS_ENUM(NSInteger, DFChooseScanType) {

DFChooseScanTypeYanquan = 1,//验券

};

@interface DFScanMaViewController : NPBaseViewController

@property (nonatomic, assign)DFChooseScanType type;

@end

.m文件

#import "DFScanMaViewController.h"

#define scan height  250

#define top height  100

// 屏幕宽高

#define NPAPPWidth [UIScreen mainScreen].bounds.size.width

#define NPAPPHeight [UIScreen mainScreen].bounds.size.height

@interface NPScanMaViewController (){

AVCaptureSession * _session;

AVCaptureVideoPreviewLayer * _layer;

AVCaptureMetadataOutput * _output;

AVCaptureDeviceInput * _input;

UIView * _superView;

int line_tag;

NSString*string;

}

@end

@implementation DFScanMaViewController

- (void)viewDidLoad {

[super viewDidLoad];

string=[NSString string];

line_tag = 1872637;

// Do any additional setup after loading the view from its nib.

[DFNavigationPublic setTitleOnTargetNav:self title:@"扫码"];

[DFNavigationPublic setBackButtonOnTargetNav:self action:@selector(selfRemoveFromSuperview)];

//判断相机权限

NSString *mediaType = AVMediaTypeVideo;

AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];

if(authStatus == AVAuthorizationStatusNotDetermined || authStatus == AVAuthorizationStatusDenied){

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"相机权限受限" message:@"请在iPhone的\"设置->隐私->相机\"选项中,允许\"哪拍\"访问您的相机." delegate:nil cancelButtonTitle:@"好的" otherButtonTitles:nil];

[alert show];

[self.navigationController popViewControllerAnimated:YES];

return;

}

CGSize scanSize=CGSizeMake(scanheight, scanheight);

CGRect scanRect=CGRectMake((NPAPPWidth-scanSize.width)/2, (NPAPPHeight-scanSize.width)/2-topheight, scanSize.width, scanSize.height);

UIView * scanRectView=[UIView new];

scanRectView.layer.borderColor=[UIColor whiteColor].CGColor;

scanRectView.layer.borderWidth=0.5;

//初始化链接对象

_session = [[AVCaptureSession alloc]init];

//高质量采集率

if([_session canSetSessionPreset:AVCaptureSessionPreset1920x1080] == YES ) {

_session.sessionPreset = AVCaptureSessionPreset1920x1080;

}else if (([_session canSetSessionPreset:AVCaptureSessionPreset1280x720] == YES )){

_session.sessionPreset = AVCaptureSessionPreset1280x720;

} else {

_session.sessionPreset = AVCaptureSessionPreset640x480;

}

//获取摄像设备

AVCaptureDevice * device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];

//创建输入流

_input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];

[_session addInput:_input];

//创建输出流

_output = [[AVCaptureMetadataOutput alloc]init];

//设置代理 在主线程里刷新

[_output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];

[_session addOutput:_output];

_output.metadataObjectTypes=@[AVMetadataObjectTypeQRCode,AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code];

_layer=[AVCaptureVideoPreviewLayer layerWithSession:_session];

_layer.videoGravity=AVLayerVideoGravityResizeAspectFill;

[self showLayer:self.view];

[self setOverlayPickerView];

[self setScanningRect:scanRect scanView:scanRectView];

}

-(void)showLayer:(UIView *)superView

{

_superView=superView;

_layer.frame=superView.layer.frame;

[self.view.layer insertSublayer:_layer atIndex:0];

}

- (void)setOverlayPickerView

{

//左侧的view

UIImageView *leftView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, (NPAPPWidth-scanheight)/2, NPAPPHeight)];

leftView.alpha = 0.5;

leftView.backgroundColor = [UIColor blackColor];

[self.view addSubview:leftView];

//右侧的view

UIImageView *rightView = [[UIImageView alloc] initWithFrame:CGRectMake((NPAPPWidth-scanheight)/2+scanheight, 0, (NPAPPWidth-scanheight)/2, NPAPPHeight)];

rightView.alpha = 0.5;

rightView.backgroundColor = [UIColor blackColor];

[self.view addSubview:rightView];

//最上部view

UIImageView* upView = [[UIImageView alloc] initWithFrame:CGRectMake((NPAPPWidth-scanheight)/2, 0, scanheight, (NPAPPHeight-scanheight)/2-topheight)];

upView.alpha = 0.5;

upView.backgroundColor = [UIColor blackColor];

[self.view addSubview:upView];

//底部view

UIImageView * downView = [[UIImageView alloc] initWithFrame:CGRectMake((NPAPPWidth-scanheight)/2,(NPAPPHeight-scanheight)/2-topheight+scanheight, scanheight, NPAPPHeight-200)];

downView.alpha = 0.5;

downView.backgroundColor = [UIColor blackColor];

[self.view addSubview:downView];

UIImageView *centerView = [[UIImageView alloc] initWithFrame:CGRectMake((NPAPPWidth-scanheight)/2, (NPAPPHeight-scanheight)/2-topheight,scanheight,scanheight)];

centerView.image = [UIImage imageNamed:@"saomiaokuang"];

centerView.contentMode = UIViewContentModeScaleAspectFit;

centerView.backgroundColor = [UIColor clearColor];

[self.view addSubview:centerView];

UIImageView *line = [[UIImageView alloc] initWithFrame:CGRectMake((NPAPPWidth-scanheight)/2, CGRectGetMaxY(upView.frame), scanheight, 2)];

line.tag = line_tag;

line.image = [UIImage imageNamed:@"saomiaoline"];

line.contentMode = UIViewContentModeScaleAspectFill;

line.backgroundColor = [UIColor clearColor];

[self.view addSubview:line];

UILabel *msg = [[UILabel alloc] initWithFrame:CGRectMake(30, CGRectGetMinY(downView.frame), NPAPPWidth-60, 60)];

msg.backgroundColor = [UIColor clearColor];

msg.textColor = [UIColor whiteColor];

msg.textAlignment = NSTextAlignmentCenter;

msg.font = [UIFont systemFontOfSize:16];

msg.text = @"将二维码放入框内,即可自动扫描";

[self.view addSubview:msg];

}

-(void)starttRunning{

[_session addObserver:self forKeyPath:@"running" options:NSKeyValueObservingOptionNew context:nil];

[_session startRunning];

}

-(void)stoppRunning{

[_session stopRunning];

[_session removeObserver:self forKeyPath:@"running" context:nil];

}

-(void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection{

if (metadataObjects.count>0) {

[self stoppRunning];

AVMetadataMachineReadableCodeObject * metadataObject = [metadataObjects objectAtIndex : 0 ];

//输出扫描字符串

string =metadataObject.stringValue;

[self performSelector:@selector(gotoScanwith) withObject:nil afterDelay:0.5];

}

}

-(void)gotoScanwith

{

if (self.type==DFChooseScanTypeYanquan) {

NSArray * objectarray = [string componentsSeparatedByString:@","]; //从字符A中分隔成2个元素的数组

}else{

}

}

-(void)removeLayer:(UIView *)superView

{

[_layer removeFromSuperlayer];

}

-(void)setScanningRect:(CGRect)scanRect scanView:(UIView *)scanView

{

CGFloat x,y,width,height;

x=((NPAPPHeight-scanheight)/2-topheight+64)/NPAPPHeight;

y=((NPAPPWidth-scanheight)/2)/NPAPPWidth;

width=scanheight/NPAPPHeight;

height=scanheight/NPAPPWidth;

_output.rectOfInterest=CGRectMake(0, 0, 1, 1);

//    _output.rectOfInterest=CGRectMake(x, y, width, height);

if (scanView) {

scanView.frame=scanRect;

if (_superView) {

[_superView addSubview:scanView];

}

}

}

- (void)observeValueForKeyPath:(NSString *)keyPath

ofObject:(id)object

change:(NSDictionary *)change

context:(void *)context{

if ([object isKindOfClass:[AVCaptureSession class]]) {

BOOL isRunning = ((AVCaptureSession *)object).isRunning;

if (isRunning) {

[self addAnimation];

}else{

[self removeAnimation];

}

}

}

//添加扫描动画

- (void)addAnimation{

UIView *line = [self.view viewWithTag:line_tag];

line.hidden = NO;

CABasicAnimation *animation = [NPScanMaViewController moveYTime:2 fromY:[NSNumber numberWithFloat:0] toY:[NSNumber numberWithFloat:scanheight] rep:OPEN_MAX];

[line.layer addAnimation:animation forKey:@"LineAnimation"];

}

- (void)removeAnimation{

UIView *line = [self.view viewWithTag:line_tag];

[line.layer removeAnimationForKey:@"LineAnimation"];

line.hidden = YES;

}

+ (CABasicAnimation *)moveYTime:(float)time fromY:(NSNumber *)fromY toY:(NSNumber *)toY rep:(int)rep

{

CABasicAnimation *animationMove = [CABasicAnimation animationWithKeyPath:@"transform.translation.y"];

[animationMove setFromValue:fromY];

[animationMove setToValue:toY];

animationMove.duration = time;

animationMove.delegate = self;

animationMove.repeatCount  = rep;

animationMove.fillMode = kCAFillModeForwards;

animationMove.removedOnCompletion = NO;

animationMove.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];

return animationMove;

}

- (void)selfRemoveFromSuperview{

[self stoppRunning];

[UIView animateWithDuration:0.3 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{

self.view.alpha = 0;

} completion:^(BOOL finished) {

[self.view removeFromSuperview];

[self removeFromParentViewController];

}];

[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault animated:YES];

[self.navigationController popViewControllerAnimated:YES];

}

-(void)viewWillAppear:(BOOL)animated

{

[super viewWillAppear:YES];

[self starttRunning];

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,736评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,167评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,442评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,902评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,302评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,573评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,847评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,562评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,260评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,531评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,021评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,367评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,016评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,068评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,827评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,610评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,514评论 2 269

推荐阅读更多精彩内容

  • 一、扫描 1、 ZBar ZBar在扫描的灵敏度上,和内存的使用上相对于ZXing上都是较优的,但是对于 “圆角二...
    空白Null阅读 942评论 0 2
  • 在iOS中随处都可以看到绚丽的动画效果,实现这些动画的过程并不复杂,今天将带大家一窥ios动画全貌。在这里你可以看...
    每天刷两次牙阅读 8,321评论 6 30
  • 一、前言 最近在做一个关于扫描二维码签到的小东西,所以还是上来写一篇关于二维码的文章,网上也有一些扫描二维码的框架...
    kim逸云阅读 4,222评论 2 8
  • 1、禁止手机睡眠[UIApplication sharedApplication].idleTimerDisabl...
    DingGa阅读 1,084评论 1 6
  • 一个好的结尾,可以使通篇溢光流彩,一个不好的结尾,却会损害小说的整体美感,产生“为山九仞,功亏一篑”的遗憾。《白石...
    白衣秀士阅读 527评论 0 1