0

我的应用程序遍历图像路径数组并将所有这些图像合并为一个。代码如下。但是,当我发布带有 (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);
4

1 回答 1

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引用的类别方法。

于 2013-01-17T22:36:02.743 回答