最近看了看,怎么在应用中生成二维码,感觉挺好玩的。以下是核心代码。
黑白二维码代码
/// 黑白二维码
- (void)test
{
// 二维码本质是字符串
// NSArray *array = [CIFilter filterNamesInCategory:kCICategoryBuiltIn];
// NSLog(@"%@",array);w
// 1.获取二维码的过滤器
CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
// 2.设置默认值
[filter setDefaults];
// 3.获取过滤器的值
NSLog(@"%@",filter.inputKeys);
// 4.设置二维码内容
NSString *string = @"哈哈哈哈哈";
// inputMessage必须使用NSData类型,否则就崩溃
[filter setValue:[string dataUsingEncoding:NSUTF8StringEncoding] forKey:@"inputMessage"];
// 5.取出图片
CIImage *ciimage = filter.outputImage;
NSLog(@"%@",ciimage);
// 修改图片大小
ciimage = [ciimage imageByApplyingTransform:CGAffineTransformMakeScale(6, 6)];
UIImage *image = [UIImage imageWithCIImage:ciimage];
self.imageView.image = image;
}
运行后的效果
彩色二维码加居中小图片
- (void)viewDidLoad {
[super viewDidLoad];
// 二维码本质是字符串
NSArray *array = [CIFilter filterNamesInCategory:kCICategoryBuiltIn];
NSLog(@"%@",array);
// 1.获取二维码的过滤器
CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
// 2.设置默认值
[filter setDefaults];
// 3.获取过滤器的值
NSLog(@"%@",filter.inputKeys);
// 4.设置二维码内容
NSString *string = @"哈哈哈哈哈";
// inputMessage必须使用NSData类型,否则就崩溃
[filter setValue:[string dataUsingEncoding:NSUTF8StringEncoding] forKey:@"inputMessage"];
// 5.取出图片
CIImage *ciimage = filter.outputImage;
// NSLog(@"%@",ciimage);
// 6.生成颜色过滤器
/*
inputImage, 需要设置颜色的图片
inputColor0, 前景色
inputColor1 背景色
*/
// 6.1颜色过滤器
CIFilter *colorFilter = [CIFilter filterWithName:@"CIFalseColor"];
// 6.2设置默认值
[colorFilter setDefaults];
// 6.3打印可以使用的值
NSLog(@"%@",colorFilter.inputKeys);
// 6.4设置添加颜色的图片
[colorFilter setValue:ciimage forKey:@"inputImage"];
// 6.5设置前景色
// [colorFilter setValue:[CIColor colorWithRed:1 green:0 blue:0 alpha:1] forKey:@"inputColor0"];
// // 6.5设置背景色
// [colorFilter setValue:[CIColor colorWithRed:0 green:1 blue:0 alpha:1] forKey:@"inputColor1"];
// 6.6获取设置完颜色的图片
// ciimage = colorFilter.outputImage;
// 7.修改图片大小
ciimage = [ciimage imageByApplyingTransform:CGAffineTransformMakeScale(6, 6)];
UIImage *image = [UIImage imageWithCIImage:ciimage];
// 8.添加中间图片
// 8.1开启图形上下文
UIGraphicsBeginImageContext(image.size);
// 8.2画二维码图片
[image drawInRect:CGRectMake(0, 0, image.size.width, image.size.height)];
// 8.3画中间的图片
UIImage *meImage = [UIImage imageNamed:@"程序员"];
CGFloat meImageW = 40;
CGFloat meImageH = 40;
CGFloat meImageX = (image.size.width - meImageW) * 0.5;
CGFloat meImageY = (image.size.height - meImageH) * 0.5;
[meImage drawInRect:CGRectMake(meImageX, meImageY, meImageW, meImageH)];
// 8.4取出图片
UIImage *finalImage = UIGraphicsGetImageFromCurrentImageContext();
// 8.5关闭图形上下文
UIGraphicsEndImageContext();
// 9.显示图片
self.imageView.image = finalImage;
}