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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
|
#import "ViewController.h"
#import <CoreImage/CoreImage.h>
@interface ViewController ()
@property (nonatomic, strong) UIImageView *imageView;
@end
@implementation ViewController
- (UIImageView *)imageView {
if (!_imageView) {
_imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 200, 200)];
_imageView.center = self.view.center;
[self.view addSubview:_imageView];
}
return _imageView;
}
- (void)viewDidLoad {
[super viewDidLoad];
[self creatQRCode];
}
// 生成二维码
- (void)creatQRCode {
// 创建二维码滤镜
CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
// 恢复滤镜的默认属性
[filter setDefaults];
// 给过滤器添加数据(纯文本,URL都可以)
// NSString *dataString = @"http://www.baidu.com";
NSString *dataString = @"生成二维码";
// 将字符串转换成NSData
NSData *data = [dataString dataUsingEncoding:NSUTF8StringEncoding];
// 设置滤镜 inputMessage 数据
[filter setValue:data forKeyPath:@"inputMessage"];
// 获取滤镜输出的二维码
CIImage *outputImage = [filter outputImage];
// 显示二维码
self.imageView.image = [self creatClearImageFromCIImage:outputImage withSize:200];
}
- (UIImage *)creatClearImageFromCIImage:(CIImage *)image withSize:(CGFloat) size
{
CGRect extent = CGRectIntegral(image.extent);
CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
size_t width = CGRectGetWidth(extent) * scale;
size_t height = CGRectGetHeight(extent) * scale;
// 创建灰度色调空间
CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceGray();
CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, colorSpaceRef, (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);
// 保存图片
CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
CGContextRelease(bitmapRef);
CGImageRelease(bitmapImage);
return [UIImage imageWithCGImage:scaledImage];
}
|