【问题标题】:iOS CAKeyframeAnimation memory issueiOS CAKeyframeAnimation 内存问题
【发布时间】:2019-01-04 06:56:28
【问题描述】:

我有 100 张 png 图片,我正在使用 CAKeyframeAnimation 生成一个可以播放动画的图层。

代码是这样的:

CAKeyframeAnimation *kfa = [CAKeyframeAnimation animationWithKeyPath:@"contents"];
kfa.values = animationImages; //CGImage type
kfa.removedOnCompletion = NO;
kfa.duration = 3.f;
kfa.repeatCount = CGFLOAT_MAX;
[layer addAnimation:kfa forKey:nil];

每张图片都是 1338*1338 像素,所以在渲染这个动画的时候,内存是天价。 (1338*1338*4B)

那么我怎样才能减少内存使用并获得可接受的性能?

【问题讨论】:

  • 答案的另一个选择可能是使用 AVAssetWriter 创建电影,但如果需要导出,我只会走这条路。

标签: ios animation memory


【解决方案1】:

这样做时我会避免关键帧动画。一个简单的计时器应该可以完成您的工作,但您也可以查看UIImageView 的本机功能。有一个属性animationImages。请查看this post。虽然这也会消耗大量的内存。

无论如何,如果您选择手动执行此操作,请确保尽快释放内存。您可能仍需要一些内部自动释放池:

@autoreleasepool {
    // Code that creates autoreleased objects.
}

我会尝试以下方法(它甚至不需要额外的自动释放池)

+ (void)animateImagesWithPaths:(NSArray *)imagePaths onImageView:(UIImageView *)imageView duration:(NSTimeInterval)duration {
    int count = (int)imagePaths.count;
    if(count <= 0) {
        // No images, no nothing
        return;
    }

    // We need to add the first image instantly
    imageView.image = [[UIImage alloc] initWithContentsOfFile:imagePaths[0]];

    if(count == 1) {
        // Nothing not animate with only 1 image. We are all done
        return;
    }

    NSTimeInterval interval = duration/(NSTimeInterval)(count-1);
    __block int imageIndex = 1; // We need to start with one as first is already consumed

    [NSTimer timerWithTimeInterval:interval repeats:true block:^(NSTimer * _Nonnull timer) {
        if(imageIndex < count) {
            imageView.image = [[UIImage alloc] initWithContentsOfFile:imagePaths[imageIndex]];
            imageIndex++;
        }
        else {
            // Animation ended. Invalidate timer.
            [timer invalidate];
        }
    }];

}

【讨论】:

  • 谢谢,是的,我刚刚提出了类似的解决方案,关键是实现 contentOfFile:.
  • @Boris 是的,如果你使用了imageNamed:,你应该注意这些图像正在被缓存。不幸的是,您无法明确清除该缓存。所以是的,contentOfFile 有时可能是一个更好的解决方案。或者更确切地说,总是在您经常处理图像时。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-18
  • 2014-06-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多