// 創(chuàng)建過濾鏡對象
CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
// 設置相關屬性
[filter setDefaults];
// 給過濾鏡添加數(shù)據(jù)
NSString *dataStr = @"http://www.baidu.com";
NSData *data = [dataStr dataUsingEncoding:NSUTF8StringEncoding];
[filter setValue:data forKey:@"inputMessage"];
// 獲取輸出的二維碼
CIImage *outputImage = [filter outputImage];
// 展示二維碼
self.outputImage.image = [self createNonInterpolatedUIImageFormCIImage:outputImage withSize:200];
/**
- 根據(jù)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.創(chuàng)建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];
}