使用iOS-QR-Code-Encoder 生成二维码

时间:2021-11-28 04:32:25

一:所需类库

iOS-QR-Code-Encoder

  官网主页:https://github.com/moqod/iOS-QR-Code-Encoder

导入:QuartzCore.framework

二:使用流程

  1. 导入libqrencode文件夹里的所有文件
  2. 在使用的地方 导入 

    #import "qrencode.h"

  3. 添加如下生成代码:
//生成二维码:

- (UIImage *)qrImageForString:(NSString *)string imageSize:(CGFloat)size {
if (![string length]) {
return nil;
} // generate QR
QRcode *code = QRcode_encodeString([string UTF8String], , QR_ECLEVEL_L, QR_MODE_8, );
if (!code) {
return nil;
} if (code->width > size) {
printf("Image size is less than qr code size (%d)\n", code->width);
return nil;
} // create context CGBitmapInfo bitmapInfo = (CGBitmapInfo) kCGImageAlphaPremultipliedLast; CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef ctx = CGBitmapContextCreate(, size, size, , size * , colorSpace, bitmapInfo); CGAffineTransform translateTransform = CGAffineTransformMakeTranslation(, -size);
CGAffineTransform scaleTransform = CGAffineTransformMakeScale(, -);
CGContextConcatCTM(ctx, CGAffineTransformConcat(translateTransform, scaleTransform)); // draw QR on this context
[self drawQRCode:code context:ctx size:size]; // get image
CGImageRef qrCGImage = CGBitmapContextCreateImage(ctx);
UIImage * qrImage = [UIImage imageWithCGImage:qrCGImage]; // free memory
CGContextRelease(ctx);
CGImageRelease(qrCGImage);
CGColorSpaceRelease(colorSpace);
QRcode_free(code); return qrImage;
} - (void)drawQRCode:(QRcode *)code context:(CGContextRef)ctx size:(CGFloat)size {
int margin = ;
unsigned char *data = code->data;
int width = code->width;
int totalWidth = width + margin * ;
int imageSize = (int)floorf(size); // @todo - review float->int stuff
int pixelSize = imageSize / totalWidth;
if (imageSize % totalWidth) {
pixelSize = imageSize / width;
margin = (imageSize - width * pixelSize) / ;
} CGRect rectDraw = CGRectMake(0.0f, 0.0f, pixelSize, pixelSize);
// draw
CGContextSetFillColor(ctx, CGColorGetComponents([UIColor blackColor].CGColor));
for(int i = ; i < width; ++i) {
for(int j = ; j < width; ++j) {
if(*data & ) {
rectDraw.origin = CGPointMake(margin + j * pixelSize, margin + i * pixelSize);
CGContextAddRect(ctx, rectDraw);
}
++data;
}
}
CGContextFillPath(ctx);
}

三:调用生成二维:

        //数据处理部分
CGFloat qrcodeLength = ;
UIImageView *imageV = [[UIImageView alloc]initWithFrame:CGRectMake((contentView.width-qrcodeLength)/, , qrcodeLength,qrcodeLength)];
//imageV.backgroundColor = [UIColor grayColor];
//添加二维码
imageV.image = [self qrImageForString:@"2013.11.11购物狂欢节" imageSize:qrcodeLength];
[contentView addSubview:imageV];

使用iOS-QR-Code-Encoder 生成二维码