生成一个二维码的小demo,只需要传入url网址就行了.
- (UIImage*)getImageWith:(NSString*)url{
// 1、创建滤镜对象
CIFilter*filter = [CIFilterfilterWithName:@"CIQRCodeGenerator"];
//恢复滤镜的默认属性
[filtersetDefaults];
// 2、设置数据
NSString*string_data = url;
//将字符串转换成NSdata (虽然二维码本质上是字符串,但是这里需要转换,不转换就崩溃)
NSData*qrImageData = [string_datadataUsingEncoding:NSUTF8StringEncoding];
//设置过滤器的输入值, KVC赋值
[filtersetValue:qrImageDataforKey:@"inputMessage"];
// 3、获得滤镜输出的图像
CIImage*outputImage = [filteroutputImage];
//图片小于(27,27),我们需要放大
outputImage = [outputImageimageByApplyingTransform:CGAffineTransformMakeScale(20,20)];
// 4、将CIImage类型转成UIImage类型
UIImage*start_image = [UIImageimageWithCIImage:outputImage];
// - - - - - - - - - - - - - - - -添加中间小图标- - - - - - - - - - - - - - - -
// 5、开启绘图,获取图形上下文(上下文的大小,就是二维码的大小)
UIGraphicsBeginImageContext(start_image.size);
//把二维码图片画上去(这里是以图形上下文,左上角为(0,0)点
[start_imagedrawInRect:CGRectMake(0,0, start_image.size.width, start_image.size.height)];
//再把小图片画上去
NSString*icon_imageName =@"520";
UIImage*icon_image = [UIImageimageNamed:icon_imageName];
CGFloaticon_imageW =200;
CGFloaticon_imageH = icon_imageW;
CGFloaticon_imageX = (start_image.size.width- icon_imageW) *0.5;
CGFloaticon_imageY = (start_image.size.height- icon_imageH) *0.5;
[icon_imagedrawInRect:CGRectMake(icon_imageX, icon_imageY, icon_imageW, icon_imageH)];
// 6、获取当前画得的这张图片
UIImage*final_image =UIGraphicsGetImageFromCurrentImageContext();
// 7、关闭图形上下文
UIGraphicsEndImageContext();
// 8、借助UIImageView显示二维码
return_qrCodeImage.image= final_image;
//CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
//NSData *data = [url dataUsingEncoding:NSUTF8StringEncoding];
//[filter setValue:data forKey:@"inputMessage"];
//CIImage *outImage = filter.outputImage;
//CIContext *context = [CIContext contextWithOptions:nil];
//CGRect extent = outImage.extent;
//CGImageRef bitmapImage = [context createCGImage:outImage fromRect:extent];
//CGFloat scale = MIN(250/CGRectGetWidth(extent), 250/CGRectGetHeight(extent));
//CGContextRef bitmapRef = CGBitmapContextCreate(nil, 250, 250, 8, 0, CGColorSpaceCreateDeviceGray(), (CGBitmapInfo)kCGImageAlphaNone);
//CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
//CGContextScaleCTM(bitmapRef, scale, scale);
//CGContextDrawImage(bitmapRef, extent, bitmapImage);
//CGImageRef scaleImage = CGBitmapContextCreateImage(bitmapRef);
//CGContextRelease(bitmapRef);
//CGImageRelease(bitmapImage);
//return _qrCodeImage.image = [UIImage imageWithCGImage:scaleImage];
}
最后运行结果如下图: