您的位置:首页 > 移动开发 > IOS开发

iOS开发之生成本地二维码

2016-05-26 16:23 253 查看
向凡神致敬~

第一步:

使用cocoapods第三方库管理工具导入libqrencode第三方库

注:libqrencode实际是UIImageView的分类

第二步:

创建一个QRCodeGenerator的类

.h文件:

#import <Foundation/Foundation.h>

#import <UIKit/UIKit.h>

@interface QRCodeGenerator : NSObject

+ (UIImage *)qrImageForString:(NSString *)string imageSize:(CGFloat)size;

@end

.m文件

#import "QRCodeGenerator.h"

#import <qrencode.h>

enum {

qr_margin = 3

};

@implementation QRCodeGenerator

+ (void)drawQRCode:(QRcode *)code context:(CGContextRef)ctx size:(CGFloat)size {

unsigned char *data = 0;

int width;

data = code->data;

width = code->width;

float zoom = (double)size / (code->width + 2.0 * qr_margin);

CGRect rectDraw = CGRectMake(0, 0, zoom, zoom);

// draw

CGContextSetFillColor(ctx, CGColorGetComponents([UIColor blackColor].CGColor));

for(int i = 0; i < width; ++i) {

for(int j = 0; j < width; ++j) {

if(*data & 1) {

rectDraw.origin = CGPointMake((j + qr_margin) * zoom,(i + qr_margin)
* zoom);

CGContextAddRect(ctx, rectDraw);

}

++data;

}

}

CGContextFillPath(ctx);

}

+ (UIImage *)qrImageForString:(NSString *)string imageSize:(CGFloat)size {

if (![string length]) {

return nil;

}

QRcode *code = QRcode_encodeString([string UTF8String], 0, QR_ECLEVEL_L, QR_MODE_8, 1);

if (!code) {

return nil;

}

// create context

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();

CGContextRef ctx = CGBitmapContextCreate(0,
size, size, 8, size * 4, colorSpace, kCGImageAlphaPremultipliedLast);

CGAffineTransform translateTransform = CGAffineTransformMakeTranslation(0, -size);

CGAffineTransform scaleTransform = CGAffineTransformMakeScale(1,
-1);

CGContextConcatCTM(ctx, CGAffineTransformConcat(translateTransform, scaleTransform));

// draw QR on this context

[QRCodeGenerator drawQRCode:code context:ctx size:size];

// get image

CGImageRef qrCGImage = CGBitmapContextCreateImage(ctx);

UIImage * qrImage = [UIImage imageWithCGImage:qrCGImage];

// some releases

CGContextRelease(ctx);

CGImageRelease(qrCGImage);

CGColorSpaceRelease(colorSpace);

QRcode_free(code);

return qrImage;

}

@end

第三步:

在需要生成本地二维码的类中导入QRCodeGenerator该类,列:#import "QRCodeGeneratir.h"

第四步:

使用qrImageForString方法生成二维码

例如(第一个参数为二维码中包含的数据,第二个参数为二维码的大小):

self.QRCodeimageView.image = [QRCodeGenerator qrImageForString:jsonStr imageSize:200];

本文有因为问题请联系

QQ:563699115

Telephone:18341266547
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: