我有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)
那么,如何减少内存使用并获得可接受的性能呢?
发布于 2019-01-04 15:34:43
在这样做的时候,我会避免使用关键帧动画。一个简单的计时器应该能够完成您的工作,但您也可以研究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];
}
}];
}https://stackoverflow.com/questions/54034342
复制相似问题