生成動態(tài)二維碼
因為最近遇到需要一個生成二維碼的功能,于是我就接觸了一下,現(xiàn)將我實現(xiàn)的步驟分享一下。
首先需要再網(wǎng)上下載一個生成二維碼的三方庫 qrencode ,點擊二維碼生成庫下載。里面有提供生成二維碼的API,返回 QRcode。

注:string:需要編碼的字符串內(nèi)容;version:版本(大小等級1~40);level:容錯等級;hint:二維碼模式。
實現(xiàn)代碼:
新建一個 #import "UIImage+QRCodeGenerator.h";
在 .m 文件里實現(xiàn)
+(UIImage *)QRCodeGenerator:(NSString *)data andQuietZone (NSInteger)iQuietZone andSize:(NSInteger)iSize?
{
? ? ? ?UIImage *ret = nil;
? ? ? ?QRcode *qr = QRcode_encodeString([data ? ? ?UIT8String]),0,QR_ECLEVEL_M,QR_MODE_8,1);
? ? ? ?NSInteger logQRSize = qr->width;
? ? ? ?NSInteger phyQRSize = logQRSize + (2 * iQuietZone);
? ? ? ?NSInteger scale? ? = iSize / phyQRSize;
? ? ? ?NSInteger imgSize? = phyQRSize * scale;
? ? ? if ( scale < 1 )
? ? ? ? ?scale = 1;
? ? ? {
? ? ? ? ? ? ?UIGraphicsBeginImageContext(CGSizeMake(imgSize,imgSize));
? ? ? ? ? ? ?CGContextRef ctx = UIGraphicsGetCurrentContext();
? ? ? ? ? ? ?CGRect bounds = CGRectMake(0,0,imgSize,imgSize);
? ? ? ? ? ? ?CGContextSetFillColorWithColor(ctx,[UIColor whiteColor].CGColor);
? ? ? ? ? ? ?CGContextFillRect(ctx,bounds);
? ? ? ? ? ? // set any 'dark' colour pixels? ? ?
? ? ? ? ? ?{? ? ? ? ?
? ? ? ? ? ? ? ? ?int x,y;? ? ? ? ? ? ? ? ?
? ? ? ? ? ? ? ? CGContextSetFillColorWithColor(ctx,[UIColor blackColor].CGColor);? ? ? ? ? ? ? ? ?
? ? ? ? ? ? ? ?for ( y=0 ; ydata[(y*logQRSize)+x] & 1 )
? ? ? ? ? ? ? CGContextFillRect(ctx,CGRectMake((iQuietZone+x)*scale, ? ? (iQuietZone+y)*scale,scale,scale));
? ? ? ? ? ?}
? ? ? ? ?// generate the UIImage
? ? ? ? CGImageRef imgRef = CGBitmapContextCreateImage(ctx);
? ? ? ? ret = [UIImage imageWithCGImage:imgRef];
? ? ? ?CGImageRelease(imgRef);
? ? ? ?UIGraphicsEndImageContext();
? ? }
QRcode_free(qr);
return ret;
? ?}
}
結(jié)果: