iOS 生成二维码

实现效果:


iOS 生成二维码_第1张图片


实现方法:

一:拼接链接,生成二维码图片

NSString * raceNoStr = [NSString stringWithFormat:@"%d",model.raceNo];

//toRaceDetailShare/100402

NSString * urlStr = [NSString stringWithFormat:@"%@rest/share/toRaceDetailShare/%@",KInnerSiteBra,raceNoStr];

self.qrImgView.image = [self getImgQRCodeWithStr:urlStr];


二:链接生成二维码


-(UIImage *)getImgQRCodeWithStr:(NSString *)str{

// 1.创建过滤器 -- 苹果没有将这个字符封装成常量

CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];

// 2.过滤器恢复默认设置

[filter setDefaults];

// 3.给过滤器添加数据(正则表达式/帐号和密码) -- 通过KVC设置过滤器,只能设置NSData类型

NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];

[filter setValue:data forKeyPath:@"inputMessage"];

// 4.获取输出的二维码

CIImage *outputImage = [filter outputImage];

// 5.显示二维码

return  [self createNonInterpolatedUIImageFormCIImage:outputImage withSize:115];

}


三:使二维码图片更清晰


- (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];

}

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