1、二维码尺寸必须是59*59及以上,否则微信内长按识别不了二维码,其他手机扫二维码可能会扫不出来
代码:
+ (UIImage *)generateQRCodeWithString:(NSString *)string size:(CGFloat)size {
if(!string || string.length==0) {
returnUIImage.new;
}
CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
//过滤器恢复默认
[filtersetDefaults];
//给过滤器添加数据<字符串长度893>
NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion: NO];
[filtersetValue:dataforKey:@"inputMessage"];
// 注: 这里如果设置H的时间 二维码太小可能会造成信息不全 无法扫描
[filtersetValue:@"M" forKey:@"inputCorrectionLevel"];
//获取二维码过滤器生成二维码
CIImage*image = [filteroutputImage];
UIImage *img = [self createNonInterpolatedUIImageFromCIImage:[image imageByApplyingTransform:CGAffineTransformMakeScale(YYScreenScale(), YYScreenScale())] WithSize:size];
returnimg;
}
+ (UIImage *)createNonInterpolatedUIImageFromCIImage:(CIImage *)image WithSize:(CGFloat)size {
CGRect extent = CGRectIntegral(image.extent);
CGFloatscale =MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
//创建bitmap
size_twidth =CGRectGetWidth(extent)*scale;
size_theight =CGRectGetHeight(extent)*scale;
CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);
CIContext *context = [CIContext contextWithOptions:nil];
CGImageRefbitmapImage = [contextcreateCGImage:imagefromRect:extent];
CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
CGContextScaleCTM(bitmapRef, scale, scale);
CGContextDrawImage(bitmapRef, extent, bitmapImage);
//保存图片
CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
// UIImage *newImage = [UIImage imageWithCGImage:scaledImage];
UIImage *newImage = [UIImage imageWithCGImage:scaledImage scale:YYScreenScale() orientation:UIImageOrientationUp];
CGContextRelease(bitmapRef);
CGImageRelease(bitmapImage);
CGColorSpaceRelease(cs);
CGImageRelease(scaledImage);
returnnewImage;
}