1. qrStr指的是的是二维码的字符串,size指的是二维码的尺寸大小
+ (UIImage *)createQrImage:(NSString *)qrStr withSize:(CGFloat)size{
// 1. 实例化二维码滤镜
CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
//2// 2. 恢复滤镜的默认属性
[filter setDefaults];
// 3. 将字符串转换成NSData
NSData *data = [qrStr dataUsingEncoding:NSUTF8StringEncoding];
// 4. 使用KVC 的方式给filter 赋值
[filter setValue:data forKey:@"inputMessage"];
// 5. 获得滤镜输出的图像
CIImage *image = [filter outputImage];
//当前生成的 二维码 image 还有很模糊的,所以需要用下面的createNonInterpolatedUIImageFormCIImage方法重绘二维码
return [self createNonInterpolatedUIImageFormCIImage:image withSize:size];
}
+ (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);
return [UIImage imageWithCGImage:scaledImage];
}