ios开发中根据url生成二维码

随着微信和支付宝收到广大吃瓜群众的热捧和使用,扫码支付已经成为了很流行的一种支付方式.很多公司都接通了微信和支付宝扫码支付的通道,那么问题来了,扫码时二维码是怎么生成的呢?废话完毕,直接上代码.

// 1. 实例化二维码滤镜
CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
// 2. 恢复滤镜的默认属性
[filter setDefaults];

// 3. 将字符串转换成NSData
//    NSString *urlStr = @"http://www.ychpay.com/down.html";//测试二维码地址
AbstractItems *item = [[AbstractItems alloc]init];
NSRange range=  [item.n59 rangeOfString:@"-"];
NSString *urlStr = [NSString stringWithFormat:@"http://118.186.1.34:9139/hatchet-posp-proxy/payView.app?phone=%@&productShort=%@",[[NSUserDefaults standardUserDefaults] objectForKey:Account],[item.n59 substringToIndex:range.location]];
NSData *data = [urlStr dataUsingEncoding:NSUTF8StringEncoding];
// 4. 通过KVO设置滤镜inputMessage数据
[filter setValue:data forKey:@"inputMessage"];

// 5. 获得滤镜输出的图像
CIImage *outputImage = [filter outputImage];

// 6. 将CIImage转换成UIImage,并放大显示 (此时获取到的二维码比较模糊,所以需要用下面的createNonInterpolatedUIImageFormCIImage方法重绘二维码)
//    UIImage *codeImage = [UIImage imageWithCIImage:outputImage scale:1.0 orientation:UIImageOrientationUp];

UIImageView *wechatImageView = [[UIImageView alloc] initWithFrame:CGRectMake(40, 30, SCREEN_WIDTH - 80, SCREEN_WIDTH - 80)];
wechatImageView.image = [self createNonInterpolatedUIImageFormCIImage:outputImage withSize:200];//重绘二维码,使其显示清晰
[self.view addSubview:wechatImageView];

此时生成二维码是成功了,但是看起来很伤眼睛啊(ps:就是相当的模糊),下面的代码就是处理模糊的方法

/**
 * 根据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.创建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];
}

经过测试,生成的二维码还是比较完美的,希望可以帮到大家.
附上github地址:https://github.com/ZSyingyu/ZYYCodePayDemo.git

你可能感兴趣的:(ios开发中根据url生成二维码)