gpt4 book ai didi

memory-leaks - 用于缩放图像的 UIGraphicsGetImageFromCurrentImageContext 内存泄漏

转载 作者:行者123 更新时间:2023-12-04 05:23:53 27 4
gpt4 key购买 nike

我的 iPhone 应用程序从服务器下载图像文件,将其存储到 NSTemporaryDirectory() 中,然后在 UI 中异步加载图像。代码流程是这样的:

  1. 显示带有加载事件指示器的 View 并在后台运行图像下载器。
  2. 下载图像后,会将其写入文件。
  3. 加载 View 中的计时器不断检查临时目录中文件的可用性,一旦可用,从文件加载图像并将图像添加到 UI。
  4. 在添加图像之前,它会被缩放到所需的大小。

问题是,我使用 UIGraphicsGetImageFromCurrentImageContext 来缩放图像。看起来图像上下文使用的内存没有被清理。随着更多文件的下载,应用内存不断增加。

下面的一些代码:

缩放图片的代码:


-(UIImage*)scaleToSize:(CGSize)size image:(UIImage *)imageref
{
UIGraphicsBeginImageContext(size);
[imageref drawInRect:CGRectMake(0, 0, size.width, size.height)];
UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return scaledImage;
}

从临时目录加载图像:


-(void)loadImageFromFile: (NSString *) path
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
UIImage * imm = [[[UIImage alloc] initWithContentsOfFile:path] autorelease];
[self performSelectorOnMainThread:@selector(insertImage:) withObject:imm waitUntilDone:YES];
[pool release];
}

将图像添加到 View (代码子集):


self.imageContainer = [[UIImageView alloc] initWithFrame:CGRectMake(0,80,320,250)];
[self addSubview:self.imageContainer];
self.imageContainer.image = [self scaleToSize:CGSizeMake(320.0f, 250.0f) image:imm];
[imageContainer release];

我在这里错过了什么?

最佳答案

避免 UIGraphicsGetImageFromCurrentImageContext 泄漏的一种方法是根本不通过调整容器大小而不是直接调整图像大小来调用它:

self.imageContainer.contentMode = UIViewContentModeScaleAspectFit;
self.imageContainer.frame = CGRectMake(self.imageContainer.frame.origin.x, self.imageContainer.frame.origin.y, 320.0f, 250.0f);

关于memory-leaks - 用于缩放图像的 UIGraphicsGetImageFromCurrentImageContext 内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3075317/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com