iOS 二维码生成 记录一下

#import <CoreImage/CoreImage.h>

@property (nonatomic, nonnull , strong) UIImageView *showImage;

#pragma mark - lazy load

- (UIImageView *)showImage

{

    if (!_showImage) {

        _showImage = [[UIImageView alloc] initWithFrame:CGRectMake(100, 100, 200, 200)];

        _showImage.backgroundColor = [UIColor lightGrayColor];

        [self.view addSubview:_showImage];

    }

    return _showImage;

}

 

// 生成二维码图片
- (void)getCodeImage
{
    //1.创建CIFilter对象
    CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    //2.恢复滤镜的默认设置
    [filter setDefaults];
    //3.把一个网站字符串转换 二进制数据
    NSString *dimensocialStr = @"http://www.baidu.com";
    NSData *data = [dimensocialStr dataUsingEncoding:NSUTF8StringEncoding];
    //4.设置 滤镜 inputMessage 属性, 该需要使用 KVC 来设置
    //通过kvc的方法  用data给filer中的inputMessage属性赋值
    [filter setValue:data forKey:@"inputMessage"];
    //5.输出二维码图片
    CIImage *image = [filter outputImage];
    
    self.showImage.image = [self createNonInterpolatedUIImageFormCIImage:image withSize:200];
}

 

// 创建高清图片
- (UIImage *)createNonInterpolatedUIImageFormCIImage:(CIImage *)image withSize:(CGFloat) size
{
    CGRect extent = CGRectIntegral(image.extent);
    //设置比例
    CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
    // 创建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);
    
    // 保存bitmap到图片
    CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
    CGContextRelease(bitmapRef);
    CGImageRelease(bitmapImage);
    return [UIImage imageWithCGImage:scaledImage];
}

 

posted @ 2018-06-05 14:37  走路蹩脚的火星人  阅读(176)  评论(0编辑  收藏  举报