使用iOS-QR-Code-Encoder 生成二维码
一:所需类库
官网主页:https://github.com/moqod/iOS-QR-Code-Encoder
导入:QuartzCore.framework
二:使用流程
- 导入libqrencode文件夹里的所有文件
- 在使用的地方 导入
#import "qrencode.h"
- 添加如下生成代码:
//生成二维码: - (UIImage *)qrImageForString:(NSString *)string imageSize:(CGFloat)size { if (![string length]) { return nil; } // generate QR QRcode *code = QRcode_encodeString([string UTF8String], 0, QR_ECLEVEL_L, QR_MODE_8, 1); 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(0, size, size, 8, size * 4, colorSpace, bitmapInfo); CGAffineTransform translateTransform = CGAffineTransformMakeTranslation(0, -size); CGAffineTransform scaleTransform = CGAffineTransformMakeScale(1, -1); 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 = 0; unsigned char *data = code->data; int width = code->width; int totalWidth = width + margin * 2; int imageSize = (int)floorf(size); // @todo - review float->int stuff int pixelSize = imageSize / totalWidth; if (imageSize % totalWidth) { pixelSize = imageSize / width; margin = (imageSize - width * pixelSize) / 2; } CGRect rectDraw = CGRectMake(0.0f, 0.0f, pixelSize, pixelSize); // 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(margin + j * pixelSize, margin + i * pixelSize); CGContextAddRect(ctx, rectDraw); } ++data; } } CGContextFillPath(ctx); }
三:调用生成二维:
//数据处理部分 CGFloat qrcodeLength = 150; UIImageView *imageV = [[UIImageView alloc]initWithFrame:CGRectMake((contentView.width-qrcodeLength)/2, 10, qrcodeLength,qrcodeLength)]; //imageV.backgroundColor = [UIColor grayColor]; //添加二维码 imageV.image = [self qrImageForString:@"2013.11.11购物狂欢节" imageSize:qrcodeLength]; [contentView addSubview:imageV];
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具