我試圖在卷軸旋轉的地方製作一個老虎機動畫。爲此,我使用drawRect在從UIView繼承的自定義類中繪製圖像。我正在使用nstimer來更新圖像的位置並調用[self setNeedsDisplay]來更新圖形。在模擬器中,它看起來非常好,但是在設備上,它非常滯後。我想知道如果我的繪圖方法有問題,或者有什麼更好的解決方案。DrawRect和NSTimer的性能問題
- (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];
}
我CoreAnimation嘗試使用的UIScrollView:
- (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];
}
}
更快,更麻煩。 – 2010-07-06 00:46:10
借調。特別是在移動設備上。 CoreAnimation比Cocoa能夠做到的最好(比如「快速」和「電池友好」)要好得多。 – 2010-07-06 00:48:27
SCROLL_TIME是.05,它只是我定義的一個浮點數。 我想所有的答案都是CoreAnimation。 CoreAnimation有一個很好的簡單例子嗎? 在附註上,在之前的嘗試中,我使用了CoreAnimation和UIScrollView(請查看上面編輯的文章)。但是,當它試圖在最後一個卷軸上停止時會引起輕微的連接,這就是爲什麼我試圖自己畫吧。 – 2010-07-06 16:42:56