生成二维码

生成二维码图片,操作如下:

//生成的二维码
+(UIImage *)getCIIamgeQRCodeGenerator:(NSString *)string{
    //创建过滤器
    CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];

    //过滤器恢复默认
    [filter setDefaults];

    //将NSString格式转化成NSData格式 ,如果String 是加密过的 直接使用 String,会导致二维码无法使用,即使是用对应的解码扫码也会无法解读
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];

    //给过滤器添加数据
    [filter setValue:data forKeyPath:@"inputMessage"];

    //获取二维码过滤器生成的二维码
    CIImage *image = [filter outputImage];

    
    CGRect extent = CGRectIntegral(image.extent);
    CGFloat scale = MIN(KMainW/CGRectGetWidth(extent), KMainW/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:image fromRect:extent];
    CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
    CGContextScaleCTM(bitmapRef, scale, scale);
    CGContextDrawImage(bitmapRef, extent, bitmapImage);

    // 2.保存bitmap到图片
    CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
    CGContextRelease(bitmapRef);
    CGImageRelease(bitmapImage);
    
    //将获取到的二维码添加到imageview上
    return [UIImage imageWithCGImage:scaledImage];
}

你可能感兴趣的:(生成二维码)