一贮尖、 導入 #import <CoreImage/CoreImage.h> 系統(tǒng)庫
二笛粘、 // 1. 創(chuàng)建一個二維碼濾鏡實例(CIFilter)
CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
// 濾鏡恢復默認設置
[filter setDefaults];
/** /2. 給濾鏡添加數(shù)據(jù)
傳 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)
/**
*? 根據(jù)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. 創(chuàng)建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