- 使用前需导入
#import <CoreImage/CoreImage.h>
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
// 1.实例化二维码滤镜 CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"]; // 2.恢复滤镜的默认属性 [filter setDefaults]; // 3.二维码信息 NSString *str = @"哎呀我去"; // 展示一串文字 // NSString *str = @"http://www.baidu.com"; // 直接打开网页 // 4.将字符串转成二进制数据 NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding]; // 5.通过KVC设置滤镜inputMessage数据 [filter setValue:data forKey:@"inputMessage"]; // 6.获取滤镜输出的图像 CIImage *outputImage = [filter outputImage]; // 7.将CIImage转成UIImage UIImage *image = [self createNonInterpolatedUIImageFormCIImage:outputImage withSize:200]; // 8.展示二维码 self.imageView.image = image; }
|
- 系统默认获取到的二维码图片不太清晰,可以利用下面的方法,获取指定大小的二维码图片
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| /** * 根据CIImage生成指定大小的UIImage * * @param image CIImage * @param 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]; }
|