首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >iOS CAKeyframeAnimation内存问题

iOS CAKeyframeAnimation内存问题
EN

Stack Overflow用户
提问于 2019-01-04 14:56:28
回答 1查看 77关注 0票数 0

我有100个png图片,我正在使用CAKeyframeAnimation生成一个层,它将播放动画。

代码如下:

代码语言:javascript
复制
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)

那么,如何减少内存使用并获得可接受的性能呢?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-01-04 15:34:43

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

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

代码语言:javascript
复制
@autoreleasepool {
    // Code that creates autoreleased objects.
}

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

代码语言:javascript
复制
+ (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];
        }
    }];

}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54034342

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档