我已经使用以下代码在我的应用程序中实现了一个QR代码生成器:
+ (UIImage *)qrCodeForString:(NSString *)qrString withScale:(CGFloat)scale {
CIImage *image = [self createQRForString:qrString];
return [self createNonInterpolatedUIImageFromCIImage:image withScale:scale];
}
+ (UIImage *)createNonInterpolatedUIImageFromCIImage:(CIImage *)image withScale:(CGFloat)scale
{
// Render the CIImage into a CGImage
CGImageRef cgImage = [[CIContext contextWithOptions:nil] createCGImage:image fromRect:image.extent];
// Now we'll rescale using CoreGraphics
UIGraphicsBeginImageContext(CGSizeMake(image.extent.size.width * scale, image.extent.size.width * scale));
CGContextRef context = UIGraphicsGetCurrentContext();
// We don't want to interpolate (since we've got a pixel-correct image)
CGContextSetInterpolationQuality(context, kCGInterpolationNone);
CGContextDrawImage(context, CGContextGetClipBoundingBox(context), cgImage);
// Get the image out
UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
// Tidy up
UIGraphicsEndImageContext();
CGImageRelease(cgImage);
return scaledImage;
}
+ (CIImage *)createQRForString:(NSString *)qrString
{
// Need to convert the string to a UTF-8 encoded NSData object
NSData *stringData = [qrString dataUsingEncoding:NSUTF8StringEncoding];
NSLog(@"Size: %zd", stringData.length);
// Create the filter
CIFilter *qrFilter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
// Set the message content and error-correction level
[qrFilter setValue:stringData forKey:@"inputMessage"];
[qrFilter setValue:@"L" forKey:@"inputCorrectionLevel"];
// Send the image back
return qrFilter.outputImage;
}问题是,如果我用长字符串调用方法+ (UIImage *)qrCodeForString:(NSString *)qrString withScale:(CGFloat)scale (但仍然远远超出QR代码所能包含的范围),那么内存的使用就会变得疯狂!在真正的设备上,应用程序(或整个设备)只是崩溃,但在模拟器中,我可以使用计算机的所有内存,在生成QR代码时,它的容量会达到1GB以上(然后下降到正常状态,没有明显的内存泄漏痕迹)。我的代码有什么问题吗,还是苹果用可笑的内存使用实现了API?
一个将产生643.7 MB内存使用的示例字符串:1234567890qesgyujfghjkoiuyhgfrty¬˙∫ç∂∆˚¨¥©√∂†¥˙˜˚˙©ƒ∂®†
运行此代码将导致以下内存使用量:生成QR代码前:49.2MB,生成QR代码: 643.7 MB,生成QR代码后:49.4MB(一些内存现在还用于在屏幕上显示图像)
发布于 2015-03-11 06:59:06
我最终发现了这个问题。在缩放图像时,我没有传递屏幕宽度与原始图像大小的比率,而是传递屏幕宽度,使图像750x750倍大。这显然导致了对记忆的巨大需求。对于简单的QR码(短字符串),这没有明显的效果,因为原始图像太小了,但是当QR码变大时,缩放也变得更需要资源。
发布于 2015-03-09 00:12:16
时间运行仪器使用分配工具,看看你是否可以找出是什么导致了巨大的内存使用高峰。
https://stackoverflow.com/questions/28932540
复制相似问题