我的应用程序循环遍历图像路径数组,并将所有这些图像合并为一个。代码如下。但是,当我在控制台中打印出(gdb)图像时,应用程序崩溃了。如果我删除图像释放行,那么它工作正常,但这可能会导致内存泄漏。请查看此代码并解释为什么会发生这种情况以及可以改进的内容。谢谢。
UIGraphicsBeginImageContextWithOptions(CGSizeMake(width*len+padding*len+padding,
height+padding*2),
YES, 0.0);
do{
//draw image
path = (NSString*)[_imageData objectAtIndex:i];
UIImage * img = [[[UIImage alloc] initWithContentsOfFile:path]
cropCenterAndScaleImageToSize:CGSizeMake(width, height)];
[img drawAtPoint: CGPointMake(width*i+padding*i+padding,padding) blendMode:kCGBlendModeNormal alpha:1];
[img release]; //APP CRASHES HERE BUT WORKS IF THIS LINE REMOVED
i++;
}while (i<len);
UIImage *result = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImageWriteToSavedPhotosAlbum(result, self,
@selector(image:didFinishSavingWithError:contextInfo:),
nil);
答案 0 :(得分:3)
问题是您没有释放分配的图像。您正在释放自动释放的裁剪图像并泄漏分配的图像。
改变这个:
UIImage * img = [[[UIImage alloc] initWithContentsOfFile:path]
cropCenterAndScaleImageToSize:CGSizeMake(width, height)];
[img drawAtPoint: CGPointMake(width*i+padding*i+padding,padding) blendMode:kCGBlendModeNormal alpha:1];
[img release];
为:
UIImage *original = [[UIImage alloc] initWithContentsOfFile:path];
UIImage *cropped = [original cropCenterAndScaleImageToSize:CGSizeMake(width, height)];
[cropped drawAtPoint:CGPointMake(width * i + padding * i + padding, padding) blendMode:kCGBlendModeNormal alpha:1];
[original release];
我假设cropCenterAndScaleImageToSize:
是一种返回自动释放的UIImage
引用的类别方法。