iOS动画一系列图像

时间:2014-04-22 14:19:04

标签: ios objective-c animation nstimer

我有一个iOS应用程序,它将一组图像和持续时间加载到一个数组中,然后我有一个显示图像的计时器,如下所示:

- (void)fireTimer:(NSTimer *)theTimer
{
    self.image = [frames objectAtIndex:currentFrame];
    NSTimeInterval time = [[durations objectAtIndex:currentFrame] floatValue];
    self.timer = [NSTimer scheduledTimerWithTimeInterval:time target:self selector:@selector(fireTimer:) userInfo:nil repeats:NO];
    currentFrame++;
    if (currentFrame >= [frames count])
    {
        currentFrame = 0;
        [timer invalidate];
    }
}

要启动动画,我调用fireTimer并循环显示图像,然后在处理完所有图像后,我调用[timer invalidate]来停止动画。我无法使用startAnimation,因为每个图像需要不同的持续时间。

正确知道我不是在后台线程上这样做,所以动画是不稳定的,因为在图像动画时会发生其他处理。

在后台制作动画的最佳方法是什么?我可以简单地将这个调用放在块中的fireTimer中吗?

我知道这可能不是在iOS上制作动画图像的最佳方法,但我现在不想对代码进行大量重构。

感谢任何有关更好解决方案的建议或示例!!!

2 个答案:

答案 0 :(得分:2)

我建议你使用UIImageView来动画你的图像:它是为了完成这个任务。如果,像你说的那样,某些图像需要比其他图像更长,那么你可以多次显示它们。假设image2需要比image1和image3显示两倍,只需在animationImages上初始化数组UIImageView,如:@[image1, image2, image2, image3]

答案 1 :(得分:0)

您可以使用performSelector: withObject: afterDelay:

,而不是使用计时器
-(void)loopBackground:(int)index
{
    if(index < [self.durations count]{
        self.image = [self.frames objectAtIndex:index];
        [self performSelector:@selector(loopBackground:) withObject:index++ afterDelay:[[self.durations objectAtIndex:index] floatValue]];
    }
}