2010-01-21 32 views
1

我已經完成了翻譯背景screen.view.m文件,但幀速率非常慢。我改變了不同的值的時間間隔,但在Iphone設備中圖像翻譯非常緩慢?任何解決方案嗎?NStimer設備緩慢?

- (id)initWithFrame:(CGRect)frame { 
if (self = [super initWithFrame:frame]) { 
    // Initialization code 
    x =0; 

    xx = 0; 
    yy = 0; 
    secX = 0; 

    [NSTimer scheduledTimerWithTimeInterval:(0.1/60) target:self selector:@selector(onTimer) userInfo:nil repeats:YES]; 
} 
return self; 

}

-(void) onTimer 
{ 
xx++; 
xx = (xx % 320); 

[self setNeedsDisplay]; 

} 



- (void)drawRect:(CGRect)rect { 
// Drawing code 


[[UIImage imageNamed:@"graphic.png"] drawAtPoint:CGPointMake(yy,xx)]; 

if(xx >= 0) 
{ 

    [[UIImage imageNamed:@"graphic.png"] drawAtPoint:CGPointMake((-320 - (-1 * xx)),yy)]; 


} 

回答

2

你似乎繪製每次圖像在你的drawRect方法。我想如果你使用UIImageView來保存UIImage,並且移動它可能會更快?

在您的.h文件中

@property (nonatomic, retain) UIImageView *myImageView; 

在你的init方法

self.myImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"graphic.png"]] autorelease]; 

,並在你的計時器回調只是移動的UIImageView像這樣

- (void) onTimer { 
    xx++; 
    xx = (xx % 320); 

    self.myImageView.center = CGPointMake(xx, self.myImageView.center.y); 
} 

(有沒有必要對於drawRect了)

希望幫助,

山姆

+0

但我想繪製DrawRect方法出於某種原因... 爲什麼NSTimer不支持它? – 2010-01-21 12:51:11

+0

即便如此,您仍然在每幀都創建一個UIImage,它可能有助於將UIImage存儲爲屬性並在init方法中創建它。你有什麼理由不能用上面的解決方案修復drawInRect方法? – deanWombourne 2010-01-21 13:32:22

+0

如果您仍然想使用-drawRect:開始佈置您的內容,那很好。您仍然希望使用Core Animation將自定義內容移動到視圖中。您甚至可能需要重新考慮計時器的使用,而只需創建一個包含您希望圖像傳播的路徑的開始點和結束點的動畫。重新繪製視圖或圖層內的內容是一項昂貴的操作,應儘可能避免。核心動畫完全是硬件加速的。 – 2010-01-21 18:39:32

1

的NSTimer工作正常。你的問題是,繪製圖像是一個相對處理器密集型任務,你每秒做600次。你只是在iPhone上淹沒相對較慢的處理器。

您需要遵循先前的建議,並使用imageview或將圖像移動到視圖內的其自己的CALayer。這樣,你只畫一次圖像,然後你可以在其他圖層中繪製任何其他圖像。

或者,您可以創建一個UIImageView,然後將其他視圖設置爲子視圖。然後,您翻譯imageview並繪製到子視圖中。

我想不出有什麼理由爲什麼一遍又一遍地繪製圖像600/sec的drawrect是最好的方法。

相關問題