0

我正在尝试制作卷轴旋转的老虎机动画。为此,我使用 drawRect 在继承自 UIView 的自定义类中绘制图像。我正在使用 nstimer 来更新图像的位置并调用 [self setNeedsDisplay] 来更新绘图。在模拟器中,它看起来非常好,但是,在设备上,它非常滞后。我想知道我的绘画方法是否有问题,或者有没有更好的解决方案。

- (void)drawRect:(CGRect)rect
{   
    [image1 drawInRect:CGRectMake(0, image1Position, 98, 80)];
    [image2 drawInRect:CGRectMake(0, image2Position, 98, 80)];
    [image3 drawInRect:CGRectMake(0, image3Position, 98, 80)];
}


- (void)spin
{
    // move each position down by 10 px
    image1Position -= MOVEMENT;
    image2Position -= MOVEMENT;
    image3Position -= MOVEMENT;
    // if any of the position <= -60 reset to 180
    if(image1Position < -50)
    {
        image1Position = 180;
    }
    if(image2Position < -50)
    {
        image2Position = 180;
    }
    if(image3Position < -50)
    {
        image3Position = 180;
    }
    [self setNeedsDisplay];
}

-(void)beginSpinAnimation
{       
    timer = [NSTimer scheduledTimerWithTimeInterval:SCROLL_TIME target:self selector:@selector(spin) userInfo:self repeats:YES];
}

我对 UIScrollView 的 CoreAnimation 尝试:

- (void) spinToNextReel
{   
    int y = self.contentOffset.y + 80;

    // if the current >= last element reset to first position (-30)
    if(y >= (80 *(elementCount+1) - 30))
    {
        y = -30;
    }

    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDuration:SCROLL_TIME];
    [UIView setAnimationCurve:UIViewAnimationCurveLinear];

    self.contentOffset = CGPointMake(0, y);

    [UIView commitAnimations];

    if (!isSpinning && targetY == y)
    {
        NSLog(@"target is %d, y is %d", targetY, y);

        if(timer)
        {
            [timer invalidate];
            timer = nil;
        }
        [self playSound];
    }
}
4

2 回答 2

4

我会说对 CoreAnimation 的研究。它是用来做你想做的事情的。它会比你在这里做的要快得多。

至于它很慢,调用 drawInRect 并不是世界上最快的事情。什么是 SCROLL_TIME?

于 2010-07-06T00:42:29.183 回答
2

你想使用CoreAnimation,它会容易很多,而且效率更高。话虽如此,如果您坚持尝试以这种方式手动制作动画,那么您做错了几件事:

  1. 不要尝试以固定的时间间隔移动恒定的量,计时器事件可能会延迟,如果它们延迟,则会导致您的动画不均匀,因为您是在每个事件而不是每个时间间隔移动恒定量。您应该在每次制作动画时记录实际时间戳,将其与之前的时间戳进行比较,并移动适当数量的像素。即使事件被延迟(实际上您将丢帧),这也会导致移动量均匀。

  2. 不要使用 NSTimer,使用CADisplayLink。这会将您的绘图与系统的本机刷新率联系起来,并将其与正在进行的任何其他绘图同步。

  3. 我知道我已经说过了,但是学习和使用 CoreAnimation,你会更快乐。

于 2010-07-06T03:10:06.670 回答