一、 导入 #import
二、 // 1. 创建一个二维码滤镜实例(CIFilter)
CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
// 滤镜恢复默认设置
[filter setDefaults];
/** /2. 给滤镜添加数据
传 URL 自动转换为链接
否则为字符信息
*/
NSString *string = @"http:www.baidu.com";
NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
// 使用KVC的方式给filter赋值
[filter setValue:data forKeyPath:@"inputMessage"];
// 3. 生成二维码
CIImage *image = [filter outputImage];
// 4. 显示二维码
/**
creatNonInterpolatedUIImageFormCIImage:(CIImage *) withSize:(CGSize *)为 UIimage 扩展类
*/
self.coderImage.image = [UIImage creatNonInterpolatedUIImageFormCIImage:image withSize:200];
UIimage 扩展类
.h
#import@interface UIImage (DBEstension)
//使用下面的方法来获得一个清晰的image
+ (UIImage *)creatNonInterpolatedUIImageFormCIImage:(CIImage *)image withSize:(CGFloat)size;
@end
.m
#import "UIImage+DBEstension.h"
@implementation UIImage (DBEstension)
/**
* 根据CIImage生成指定大小的UIImage
*
* @param image CIImage
* @param size 图片宽度 越大越清晰
*
* @return 生成的高清的UIImage
*/
+ (UIImage *)creatNonInterpolatedUIImageFormCIImage:(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];
}
@end