2010-04-07 57 views
1

我目前正在開發iPhone應用程序,而且我正在努力製作一些動畫。基於觸摸的iPhone動畫

基本上我有109幀用於在屏幕上拖動一個人,所以我正在做的是傾聽觸摸,並計算我需要切換到哪些幀。

這工作都很好,但過了一段時間後,我得到一個內存泄漏,應用程序崩潰。我在啓動時將所有圖像加載到數組中,並使用UIImageView來顯示圖像。圖像使用imageWithContentsOfFile:加載。

什麼是我最好的辦法呢?

繼承人一些源代碼:

- (void)viewWillAppear:(BOOL)animated { 
animationQueue = [[NSMutableArray alloc] initWithObjects:0]; 
imageArray = [[NSMutableArray alloc] initWithObjects:nil]; 
for(int i = 1;i<110;i++) 
{ 
    [imageArray addObject:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:[NSString stringWithFormat: @"%i", i] ofType:@"png"]]]; 
} 
[super viewWillAppear:animated];} 

查看有沒有加載代碼:

- (void)viewDidLoad { 
animation = [[UIImageView alloc] initWithFrame: CGRectMake(0, 0, 480, 320)]; 
animation.contentMode = UIViewContentModeCenter; 
[self.view addSubview:animation]; 
animation.image = [imageArray objectAtIndex:40]; 
[super viewDidLoad];} 

潤色處理程序:

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { 
// Enumerates through all touch objects 
for (UITouch *touch in touches) { 
    CGPoint touch_point = [touch locationInView:self.view]; 
    // calculate which frame to end on 
    int pos = ceil((touch_point.x/480) * 108); 
    [self redrawAnimation:pos]; 
}} 

重繪動畫:

- (void)redrawAnimation:(int)end_frame { 
    animation.image = [imageArray objectAtIndex:end_frame]; 
} 

當您沿着屏幕滑動手指幾次時,應用程序崩潰。

+0

你能發佈一些你的代碼,並告訴我們點,應用程序崩潰? – schaechtele 2010-04-07 09:51:58

+0

當您沿着屏幕滑動手指幾次時,應用程序崩潰。 – user310729 2010-04-07 12:23:21

回答

0

這不是分配太多內存的問題嗎? 110張圖片可能會佔用太多。如何在變化:

- (void)redrawAnimation:(int)end_frame { 
    animation.image = [imageArray objectAtIndex:end_frame]; 
} 

到:

- (void)redrawAnimation:(int)end_frame { 
    animation.image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] 
            pathForResource:[NSString stringWithFormat: @"%i", end_frame] 
               ofType:@"png"]]]; 
} 

在不預先分配的圖像 - (空)viewWillAppear中:(BOOL)動畫。

我知道,它會慢很多,但如果是內存限制的情況下,你寧願別無選擇。您也可以嘗試預先分配一個序列的一部分,但如果您的圖像製作動畫速度比裝入的速度快,則最終可能會導致緩衝區餓死。

+0

謝謝!無需預加載圖像,效果更好,並且仍然具有所需的效果。 – user310729 2010-04-07 18:26:14

0

難道是,你的位置int有時有一個值,爲什麼數組中沒有索引?

我的意思是這行:

int pos = ceil((touch_point.x/480) * 108); 
[self redrawAnimation:pos]; 

什麼是調試器的錯誤信息,如果該應用程序崩潰?

0

你不會說實際的碰撞是什麼,這可能是一個重要的線索。但是我願意猜測,根據你的位圖的大小,你只是在內存中佔用太多。

UIImage通常在幕後非常聰明。例如。在你的viewWillAppear中,儘管你創建了110個圖像引用,但它可能不會在需要的時候加載這些文件。當你圍繞一堆移動你的手指時,你認爲這是實際調用/加載所有幀所需要的嗎?這可能是因爲你在通往某處的路上遇到了限制? UIImage也被稱爲在低內存情況下巧妙地刷新位圖數據,但它對調用者來說有點黑盒子。

確切地說出應用程序崩潰的位置。還要考慮運行儀器來分析內存使用情況以及什麼。它可能是與內存無關的東西(在你的代碼中的其他地方有一個錯誤?)。或嘗試使用一半或四分之一的圖像等,看看會發生什麼。

如果事實證明是資源管理,如果您通過快速創建和釋放UIImages(或以某種窗口/批處理預加載方式)明確管理內存,或檢出Cocos2D或甚至是原始的OpenGL,用於適當的精​​靈/紋理,其中對這個東西的控制更容易獲得(以更多管道爲代價)。