本文授權轉載,作者:Migi000(簡書)
關於二維碼生成,網上也是有很多,三方庫也是有的如zxing,也是挺好用,這裡介紹的是通過CIFilter創建二維碼。
iOS7之後,可以使用原生的CIFilter創建二維碼,下面是相應的代碼
首先是二維碼的生成,使用CIFilter很簡單,直接傳入生成二維碼的字符串即可:
- (CIImage *)createQRForString:(NSString *)qrString { NSData *stringData = [qrString dataUsingEncoding:NSUTF8StringEncoding]; // 創建filter CIFilter *qrFilter = [CIFilter filterWithName:@"CIQRCodeGenerator"]; // 設置內容和糾錯級別 [qrFilter setValue:stringData forKey:@"inputMessage"]; [qrFilter setValue:@"M" forKey:@"inputCorrectionLevel"]; // 返回CIImage return qrFilter.outputImage; }
因為生成的二維碼是一個CIImage,我們直接轉換成UIImage的話大小不好控制,所以使用下面方法返回需要大小的UIImage:
下面同事添加了水印
- (UIImage *)createNonInterpolatedUIImageFormCIImage:(CIImage *)image withSize:(CGFloat) size { CGRect extent = CGRectIntegral(image.extent); CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent)); // 1.創建bitmap; size_t width = CGRectGetWidth(extent) * scale; size_t height = CGRectGetHeight(extent) * scale; CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray(); CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone); CIContext *context = [CIContext contextWithOptions:nil]; CGImageRef bitmapImage = [context createCGImage:image fromRect:extent]; CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone); CGContextScaleCTM(bitmapRef, scale, scale); CGContextDrawImage(bitmapRef, extent, bitmapImage); // 2.保存bitmap到圖片 CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef); CGContextRelease(bitmapRef); CGImageRelease(bitmapImage); //原圖 UIImage *outputImage = [UIImage imageWithCGImage:scaledImage]; UIGraphicsBeginImageContextWithOptions(outputImage.size, NO, [[UIScreen mainScreen] scale]); [outputImage drawInRect:CGRectMake(0,0 , size, size)]; //水印圖 UIImage *waterimage = [UIImage imageNamed:@"icon"]; [waterimage drawInRect:CGRectMake((size-waterImagesize)/2.0, (size-waterImagesize)/2.0, waterImagesize, waterImagesize)]; UIImage *newPic = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return newPic; }
以上是代碼的一些匯總,希望能幫到大家,共同努力!