我想在另一个背景图像上轻松地混合一个UIImage,因此编写了一个UIImage的分类方法,该方法来自于基于顶图像α/透明性的混合两幅图像:
- (UIImage *) blendedImageOn:(UIImage *) backgroundImage {
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
UIGraphicsBeginImageContext(backgroundImage.size);
CGRect rect = CGRectMake(0, 0, backgroundImage.size.width, backgroundImage.size.height);
[backgroundImage drawInRect:rect];
[self drawInRect:rect];
UIImage* blendedImage = [UIGraphicsGetImageFromCurrentImageContext() retain];
UIGraphicsEndImageContext();
[pool release];
return [blendedImage autorelease];
}不幸的是,我的应用程序使用上述方法加载了大约20张图像,并将其与背景图像和光泽度图像(因此可能有大约40个调用)混合在一起,正在被丢弃在设备上。
一次仪器会话显示,调用drawInRect:产生的对malloc的调用负责大部分内存的使用。我尝试将drawInRect: messages替换为对CGContextDrawImage函数的等效函数调用,但没有帮助。AutoReleasePool是在我发现内存使用问题之后添加的;它也没有什么区别。
我认为这可能是因为我没有恰当地使用图形上下文。在循环中调用上面的方法会不会是个坏主意,因为我创建了大量的上下文?还是我错过了什么?
UIImage *blendedImage = [newImage blendedImageOn:backgroundImage];我添加了自动释放池,以确保图像在主自动释放池发布之前发布,因此理论上所有新的UIImages对象都应该在循环完成后释放。分析结果不显示任何差异,无论自动释放池是否在那里。
我想问的那个问题(我承认,非常严重!)为什么20次调用此方法会导致大量内存使用?
发布于 2010-06-09 01:42:50
我发现了内存使用过度的问题。我的图像比我预期的要大得多,在调用posted方法将背景图像调整到视图大小之前,该方法将它们吸引到图形上下文中,从而解决了内存使用问题。
当图像上下文结束时,我仍然很困惑为什么内存不被回收。
发布于 2010-06-02 21:38:51
不应该直接调用drawRect:方法。使用[self setNeddsDisplay];代替(它不会帮助您处理这个漏洞);
关于你的泄密。移除泳池的所有东西。您的方法返回自动释放的UIImage对象。请在您使用返回的UIImage的地方粘贴代码,我将能够帮助您。很有可能,您应该在调用blendedImageOn:的地方设置池,并在每次3-5次迭代时排出池。
发布于 2010-06-03 00:09:47
代码的一个问题是,您得到的blendedImage对象被标记为自动释放,而当您发布临时的自动释放池poof时,您也会释放blendedImage。
您可以保留直到池被释放,然后返回它自动释放:
...
UIImage* blendedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
[blendedImage retain]; // keep this past pool release
[pool release];
[blendedimage autorelease]; // now it will be autoreleased from the main pool
return [blendedImage release]; // release to balance out the retain abovehttps://stackoverflow.com/questions/2961770
复制相似问题