OC中生成二维码
2016-09-09 本文已影响729人
打电话记错号码的人
作品链接:
http://www.jianshu.com/users/1e0f5e6f73f6/top_articles
CIFilter是在 <CoreImage/CoreImage.h>框架集成
// 1.创建滤镜对象
CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
// 2.恢复默认设置
[filter setDefaults];
// 3.设置数据
NSString *info = @"http://www.taobao.com";
NSData *infoData = [info dataUsingEncoding:NSUTF8StringEncoding];
[filter setValue:infoData forKey:@"inputMessage"];
// 4.生成二维码
CIImage *outputImage = [filter outputImage];
self.imageView.image = [self createNonInterpolatedUIIamgeFormCIImage:outputImage withSize:300];
- 生成清晰的二维码
/**
* 根据CIImage生成指定大小的UIImage 生成清晰的二维码
*
* @param image CIImage
* @param size 图片宽度
*/
- (UIImage *)createNonInterpolatedUIIamgeFormCIImage:(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 = CGColorSpaceCreateDeviceCMYK();
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];
}