-
二维码需要用到 Quartz 2D 一般是三步走~1导入CoreImage框架,编写字符串转二维码图;2渲染二维码;3显示二维码.
导入头文件
#import <CoreImage/CoreImage.h>
-
字符转二维码图
代码如下:
/**
* 创建二维码
*
* @param string string 输入待转二维码的字符串
*
* @return 二维码
*/
- (CIImage *)createTwoDimensionCodeWithString:(NSString *)string {
CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
[filter setDefaults];
NSData *data = [ string dataUsingEncoding:NSUTF8StringEncoding];
[filter setValue:data forKey:@"inputMessage"];
CIImage *image = [filter outputImage];
return image;
}
3.渲染改变
/**
* 改变图片渲染
*
* @param image 待渲染的二维码图片
* @param size 渲染大小
*
* @return 返回渲染的二维码
*/
- (UIImage *)createNonInterpolatedUIImageFormCIImage:(CIImage *)image withSize:(CGFloat) size {
CGRect extent = CGRectIntegral(image.extent);
//设置比例
CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
// 创建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);
// 保存bitmap到图片
CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
CGContextRelease(bitmapRef);
CGImageRelease(bitmapImage);
return [UIImage imageWithCGImage:scaledImage];
}
4.显示二维码
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
CIImage *image = [self createTwoDimensionCodeWithString:@"爱我你怕了吗?"];
// CIImage *image = [self createTwoDimensionCodeWithString:@"www.baidu.com"];
UIImage *img = [self createNonInterpolatedUIImageFormCIImage:image withSize:300];
UIImageView *imgView = [[UIImageView alloc]initWithImage:img];
imgView.frame = CGRectMake(10, 50, 300, 300);
[self.view addSubview:imgView];
}