生成動(dòng)態(tài)二維碼
因?yàn)樽罱龅叫枰粋€(gè)生成二維碼的功能居灯,于是我就接觸了一下,現(xiàn)將我實(shí)現(xiàn)的步驟分享一下肤寝。
首先需要再網(wǎng)上下載一個(gè)生成二維碼的三方庫 qrencode 眶根,點(diǎn)擊二維碼生成庫下載重慢。里面有提供生成二維碼的API,返回 QRcode。
注:string:需要編碼的字符串內(nèi)容先紫;version:版本(大小等級(jí)1~40)衩茸;level:容錯(cuò)等級(jí);hint:二維碼模式藐窄。
實(shí)現(xiàn)代碼:
新建一個(gè) #import "UIImage+QRCodeGenerator.h"资昧;
在 .m 文件里實(shí)現(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é)果: