开发者

UIGraphicsGetImageFromCurrentImageContext memory leak for scaling image

开发者 https://www.devze.com 2023-01-04 05:04 出处:网络
My iPhone application downloads image files from a server, stores it into NSTemporaryDirectory() and then loads the image in the UI asynchronously. Code flow is like this:

My iPhone application downloads image files from a server, stores it into NSTemporaryDirectory() and then loads the image in the UI asynchronously. Code flow is like this:

  1. Show view with loading activity indicator and run a image downloader in the background.
  2. Once the image is downloaded, it is written to a file.
  3. A timer in the lo开发者_如何学运维ading view keep checking for the availability of file in the temp directory and once available, loads the image from file and adds the image to the UI.
  4. Before adding the image, it is scaled to required size.

Problem is, I use UIGraphicsGetImageFromCurrentImageContext to scale the image. Looks like the memory used by the image context is not getting cleaned. The app memory just keeps increasing as more files get downloaded.

Some code below:

Code to scale the image:


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

Loading image from temp directory:


-(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];
}

Adding image to view (subset of code):


 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];

What am I missing here ?


One way of avoiding the leak from UIGraphicsGetImageFromCurrentImageContext is to not call it at all by resizing the container instead of resizing image directly:

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

精彩评论

暂无评论...
验证码 换一张
取 消