【发布时间】:2010-06-02 21:35:15
【问题描述】:
我想轻松地将 UIImage 混合到另一个背景图像之上,所以为 UIImage 编写了一个类别方法,改编自 blend two uiimages based on alpha/transparency of top image:
- (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 次调用),正在设备上被抛弃。
Instruments 会话显示,源自对 drawInRect: 的调用对 malloc 的调用是造成大部分内存使用的原因。我尝试用对函数 CGContextDrawImage 的等效函数调用替换 drawInRect: 消息,但它没有帮助。 AutoReleasePool是我发现内存使用问题后添加的;它也没有什么不同。
我想这可能是因为我没有正确使用图形上下文。由于我创建的上下文数量,在循环中调用上述方法是一个坏主意吗?还是我只是错过了什么?
- 编辑1:感谢cmets。该方法在设置 20 个视图的控制器方法中调用,因此在循环中我有以下调用:
UIImage *blendedImage = [newImage blendedImageOn:backgroundImage];
我添加了自动释放池以确保图像在主自动释放池释放它们之前被释放,所以理论上所有新的 UIImages 对象都应该在循环完成时释放。无论自动释放池是否在其中,分析结果都没有显示任何差异。
- 编辑 2:是的,我尝试在调用 blendedImageOn: 之前添加一个自动释放池,但没有效果。
- 编辑 3:修复了 UIImage 由于自动释放池而被释放的尴尬错误。自动释放池的目的是释放结果 UIImage 之外的任何对象,以防由于添加到主自动释放池中的临时对象未立即释放而导致内存过多。
我试图问的问题(非常糟糕,我承认!)是:为什么调用此方法 20 次会导致大量内存使用?
【问题讨论】:
标签: iphone memory-management uiimage