#import "ViewController.h"
#import
#define screenW [UIScreen mainScreen].bounds.size.width
#define screenH [UIScreen mainScreen].bounds.size.height
@interface ViewController ()
@property(nonatomic,strong) UIImageView *imageView;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
CGFloat imgW = screenW * 0.5;
CGFloat imgH = imgW;
CGFloat imgX = (screenW - imgW)/2;
CGFloat imgY = (screenH - imgW)/2;
CGRect imgRect = {imgX,imgY,imgW,imgH};
self.imageView = [[UIImageView alloc] initWithFrame:imgRect];
self.imageView.backgroundColor = [UIColor redColor];
[self.view addSubview:self.imageView];
}
- (void)touchesBegan:(NSSet
// 1. 创建一个二维码滤镜实例(CIFilter)
CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
// 滤镜恢复默认设置
[filter setDefaults];
// 2. 给滤镜添加数据
NSString *string = @"学号:3180807001 \n 姓名:黄振锋";
NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
// 使用KVC的方式给filter赋值
[filter setValue:data forKeyPath:@"inputMessage"];
// 3. 生成二维码
CIImage *image = [filter outputImage];
//4.在中心增加一张图片
UIImage *img = [self createNonInterpolatedUIImageFormCIImage:image withSize:screenW];
//5.把中央图片划入二维码里面
//5.1开启图形上下文
UIGraphicsBeginImageContext(img.size);
//5.2将二维码的图片画入
[img drawInRect:CGRectMake(0, 0, img.size.width, img.size.height)];
UIImage *centerImg = [UIImage imageNamed:@"HZhenF"];
CGFloat centerW=img.size.width*0.3;
CGFloat centerH=centerW;
CGFloat centerX=(img.size.width-centerW)*0.5;
CGFloat centerY=(img.size.height -centerH)*0.5;
[centerImg drawInRect:CGRectMake(centerX, centerY, centerW, centerH)];
//5.3获取绘制好的图片
UIImage *finalImg=UIGraphicsGetImageFromCurrentImageContext();
//5.4关闭图像上下文
UIGraphicsEndImageContext();
//6.显示最终二维码
self.imageView.image = finalImg;
}
/**
* 调用该方法处理图像变清晰
* 根据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];
}
@end