OC - iOS - 二维码尺寸重绘

为CIImage添加类目

#import 
#import 

@interface CIImage (Extension)
/**
 *  根据CIImage生成指定大小的UIImage
 *
 *  @param size  图片宽度
 */
- (UIImage *)createNonInterpolatedWithSize:(CGFloat)size;

@end
#import "CIImage+Extension.h"

@implementation CIImage (Extension)


/**
 *  根据CIImage生成指定大小的UIImage
 *
 *  @param size  图片宽度
 */
- (UIImage *)createNonInterpolatedWithSize:(CGFloat)size
{
    CGRect extent = CGRectIntegral(self.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:self 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

使用

// 引入库名和类目
#import 
#import "CIImage+Extension.h"
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
 // 1.创建滤镜对象
    CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    
    // 2.恢复默认设置
    [filter setDefaults];
    
    // 3.设置数据
    NSString *info = @"http://www.baidu.com";
    NSData *infoData = [info dataUsingEncoding:NSUTF8StringEncoding];
    [filter setValue:infoData forKeyPath:@"inputMessage"];
    
    // 4.生成二维码
    CIImage *outputImage = [filter outputImage];
    self.imageView.image = [outputImage createNonInterpolatedWithSize:200];  
}

你可能感兴趣的:(OC - iOS - 二维码尺寸重绘)