我该如何在iOS中动画200多张图片?

我有超过200张图像,我希望在大约10秒的空间内制作动画。 我尝试通过将图像加载到数组中然后调用startAnimating方法来使用animationImages 。 这在模拟器中运行正常但是撞毁了iPad。

我曾尝试每隔NStimer调用一次NStimer ,并在每次定时器触发时更改图像。 这比以前的方法表现更好,它在模拟器中运行良好,但在iPad的(滞后)动画结束时也崩溃了。

有人可以帮助我,告诉我解决这个问题的理想方法吗? 谢谢。

原始代码:

 - (void) humptyFallingAnim { NSString *filename; if (humptyImageCounter < 285) { filename = [NSString stringWithFormat:@"Humpty Animation HD1.2 png sequence/humpty_HD1.2_%d.png", humptyImageCounter]; UIImage *someImage = [UIImage imageNamed:filename]; humptyFalling.image = someImage; NSLog(@"loaded image: %d", humptyImageCounter); humptyImageCounter++; } else { NSLog(@"Timer invalidated"); [humptyTimer invalidate]; humptyTimer = nil; } } 

编辑:一些不适合我的新代码

 NSString *filename; if (humptyImageCounter < 285) { filename = [NSString stringWithFormat:@"Humpty Animation HD1.2 png sequence/humpty_HD1.2_%d.png", humptyImageCounter]; @autoreleasepool { UIImage *someImage = [UIImage imageWithContentsOfFile:filename]; humptyFalling.image = someImage; NSLog(@"loaded image: %d", humptyImageCounter); } humptyImageCounter++; } else { NSLog(@"Timer invalidated"); [humptyTimer invalidate]; humptyTimer = nil; } 

编辑2:

 -(void) motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event { NSLog(@"You shook it!"); [self.view bringSubviewToFront:imgSnail]; if (deviceHasBeenShaken == 0) { deviceHasBeenShaken = 1; } humptyTimer = [NSTimer scheduledTimerWithTimeInterval:(1/25) target:self selector:@selector(humptyFallingAnim) userInfo:nil repeats:YES]; [self moveHumptyPosition]; } 

不幸的是,这听起来像OpenGL ES的工作。 应用程序是游戏吗?

内存管理 :)。

 NSString* somePath; UIImageView *imageView; for (i=0;i<200;i++) { @autoreleasepool { UIImage *someImage = [UIImage imageWithContentsOfFile:somePath]; imageView.image = someImage; //every time this line is executed, old reference disappears and previous UIImage is discarded } } 

我的意思是,你必须实现autoreleasepools并且不要使用+(UIImage *)imageNamed:方法,因为它会缓存图像。

更新让我解释一下。 您的问题与内存管理有关。 您的应用必须有效地使用设备的内存,但实际上并非如此。 我不知道你的应用程序是如何工作的,但总体思路如上所示。 更新2让我知道您是否使用ARC。

更新3对不起我的奇怪语言,但已经很晚了。 原谅我 :)

尝试使用CALayer隐式动画。 创建图层并在循环中设置图像,如下所示:

 NSMutableArray *allLayers = [NSMutableArray array]; for (int i = 0 ; i != 200 ; i++) { CGImageRef image = ...; // Get i-th image from an image source CALayer* sub = [CALayer layer]; sub.contents = (__bridge id)image; sub.contentsRect = CGRectMake(...); // Create a rectangle based on the image size [self.layer addSublayer:sub]; [allLayers addObject:sub]; } 

现在,您可以通过设置其属性来隐式启动图层动画:

 for (CALayer *sub in allLayers) { sub.position = CGMakePoint(...); // The position to which to move the image } 

完成图层后,从superview中删除它们:

 for (CALayer *sub in allLayers) { [sub removeFromSuperlayer]; } 

使用cocos2d我的朋友。 省去头痛。 你所说的是用OpenGLES提高效率的百倍。 但是,OpenGL是不必要的复杂,cocos2d提供了一个很好的抽象层,所以你可以用几行代码来完成它。