/**
* 直接生成带logo的二维码
*
* @param data 二维码 data
* @param size 宽或高
* @param logo logo图片
*
* @return 返回二维码图片
*/
+ (UIImage *)generateQRCodeData:(NSData *)data
size:(CGFloat)size
logo:(UIImage *)logo {
// 创建filter
CIFilter *qrFilter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
// 设置内容和纠错级别
[qrFilter setValue:data forKey:@"inputMessage"];
/**
inputCorrectionLevel
等级 容错率 容错率越低,二维码看着越简单
L 7%
M 15% 默认值
Q 25%
H 30%
*/
[qrFilter setValue:@"L" forKey:@"inputCorrectionLevel"];
CGRect extent = CGRectIntegral(qrFilter.outputImage.extent);
CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
// 创建bitmap;
size_t width1 = CGRectGetWidth(extent) * scale;
size_t height1 = CGRectGetHeight(extent) * scale;
CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
CGContextRef bitmapRef = CGBitmapContextCreate(nil, width1, height1, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);
CIContext *context = [CIContext contextWithOptions:nil];
CGImageRef bitmapImage = [context createCGImage:qrFilter.outputImage fromRect:extent];
CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
CGContextScaleCTM(bitmapRef, scale, scale);
CGContextDrawImage(bitmapRef, extent, bitmapImage);
// 保存bitmap到图片
CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
CGContextRelease(bitmapRef);
CGImageRelease(bitmapImage);
// 将logo绘制到二维码上面
CGImageRef midImage = [UIImage imageWithCGImage:scaledImage].CGImage;
UIImage *qrImage = [UIImage imageWithCGImage:midImage];
CGFloat pading = 0;
if (logo) {
CGFloat qrSize = qrImage.size.width;
//UIGraphicsBeginImageContext(qrImage.size);
UIGraphicsBeginImageContextWithOptions(qrImage.size, NO, [UIScreen mainScreen].scale);
[qrImage drawInRect:(CGRectMake(0, 0, qrImage.size.width, qrImage.size.height))];
CGFloat x = qrSize/2 - logo.size.width/2;
CGFloat y = qrSize/2 - logo.size.height/2;
[logo drawInRect:(CGRectMake(x, y, logo.size.width, logo.size.height))];
UIImage *img2=UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIGraphicsBeginImageContextWithOptions(img2.size, NO, [UIScreen mainScreen].scale);
#pragma mark 特殊处理, 尽量使内填充为0
CGRect rect1 = CGRectMake(-pading, -pading, size+pading*2, size+pading*2);
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextTranslateCTM(ctx, rect1.origin.x, rect1.origin.y);
CGContextTranslateCTM(ctx, 0, rect1.size.height);
CGContextScaleCTM(ctx, 1.0, -1.0);
CGContextTranslateCTM(ctx, -rect1.origin.x, -rect1.origin.y);
CGContextDrawImage(ctx, rect1, img2.CGImage);
UIImage *QRImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return QRImage;
}
else {
return qrImage;
}
}
网友评论