0

我正在使用 CAKeyFrameAnimation 为几个 png 图像设置动画。我通过使用从一个 png 图像中剪切它们CGImageCreateWithImageInRect

当我在 XCode 中运行分析函数时,它显示了潜在的内存泄漏。他们是因为CGImageCreateWithImageInRect. 但是当我在创建动画对象后使用 CGImageRelease 时,没有显示图像(我知道为什么,但是当我不使用 release 时,会出现泄漏)。

有人可以解释一下这个内存问题的情况吗?什么是最好的解决方案?我正在考虑为每个“剪辑”创建带有 CGImageRefs 的 UIImages。但是 CAKeyFrameAnimation 使用 CGImageRef 的字段,所以我认为没有必要创建那个 UIImages。

UIImage *source = [UIImage imageNamed:@"my_anim_actions.png"];

cutRect = CGRectMake(0*dimForImg.width,0*dimForImg.height,dimForImg.width,dimForImg.height);
CGImageRef image1 = CGImageCreateWithImageInRect([source CGImage], cutRect);
cutRect = CGRectMake(1*dimForImg.width,0*dimForImg.height,dimForImg.width,dimForImg.height);
CGImageRef image2 = CGImageCreateWithImageInRect([source CGImage], cutRect);

NSArray *images = [[NSArray alloc] initWithObjects:(__bridge id)image1, (__bridge id)image2, (__bridge id)image2, (__bridge id)image1, (__bridge id)image2, (__bridge id)image1, nil];

CAKeyframeAnimation *myAnimation = [CAKeyframeAnimation animationWithKeyPath: @"contents"];
myAnimation.calculationMode = kCAAnimationDiscrete;
myAnimation.duration = kMyTime;
myAnimation.values = images; // NSArray of CGImageRefs
[myAnimation setValue:@"ANIMATION_MY" forKey:@"MyAnimation"];
myAnimation.removedOnCompletion = NO;
myAnimation.fillMode = kCAFillModeForwards;

CGImageRelease(image1);CGImageRelease(image2);//YES or NO
4

2 回答 2

0

不确定这是否有帮助,但我遇到了类似的情况,使用CGImageCreateWithImageInRect拍摄图像的各个部分然后在图像视图中显示这些部分会导致大量内存使用。而且我发现可以大大提高内存使用率的一件事是将子图像编码为 PNG 数据,然后再次将其重新解码回图像。

我知道,这听起来很荒谬而且完全多余,对吧?但它帮助很大。根据文档CGImageCreateWithImageInRect

生成的图像保留了对原始图像的引用,这意味着您可以在调用此函数后释放原始图像。

似乎在显示图像时,UI 会复制图像数据,包括复制它所引用的原始图像数据;这就是它使用这么多内存的原因。但是当您将其写入PNG并再次返回时,您会创建一个独立的图像数据,它更小并且不依赖于原始数据。这只是我的猜测。

无论如何,尝试一下,看看它是否有帮助。

于 2014-01-16T10:07:34.563 回答
0

两种解决方案:

第一:用于[UIImageView animationImages]在多个图像之间制作动画。

第二:将图像存储为 Ivar 并将它们发布到dealloc您的班级中。

于 2012-09-14T12:24:09.683 回答