2013-02-21 91 views
0

我有一個函數可以改變需要很長時間才能完成的圖像(大約10s)。這個圖像改變了每次迭代,我想每次都顯示它。在每次迭代後顯示UIImage

我想

self.imageView.image = [ /* function that changes image */ ]; 

,但我接受,爲什麼這是行不通的。

我也試過如下:

self.imageView.animationImages = [NSArray arrayWithObjects:[self.brain newImage], 
                  [self.brain newImage], 
                  nil]; 

,但它需要很長的時間,動畫開始之前。

如何在每次調用函數時更新動畫?

注意:[self.brain newImage]是一個有效的函數,它返回一個UIImage,並且每次都會更改。我沒有包含實際的代碼,因爲它很複雜而不是問題。

回答

0

如果animationImages方法是細跟你,你可以把它的啓動速度更快,通過預先創建的圖像:

//-- preload images (e.g., while the app is loading) 
NSArray* images = [NSArray arrayWithObjects:[self.brain newImage], 
                 [self.brain newImage], 
                 nil]; 
//-- display animation 
self.imageView.animationImages = images; 

請記住,animationImages方法有侷限性,主要的事實,你需要提前創建所有圖像 - 這可能佔用大量內存。

一種替代方法是使用CALayerNSTimer:每次觸發時,您將layer.contents設置爲下一個圖像。有關此方法的更多信息,請參閱this

對於更高級的方法,你可以求助於cocos2d或openGL,但這可能是矯枉過正。

+0

這就是我試圖避免的。加載應用程序時,圖像的生成需要很長時間才能完成。我會研究你的第二種方法。 – Scott 2013-02-22 00:15:40

+0

是的,'animationImages'非常易於使用,但它不能提供很多控制。 'CALayer' +定時器方法肯定更靈活,而且也不復雜。 – sergio 2013-02-22 08:13:15

0

考慮添加塊參數到您的-newImage方法:

- (void)newImageWithSuccessBlock:(void (^)(UIImage *newImage))successBlock 
{ 
    // generate the image on a background thread 
    UIImage *brainImage = ... 

    // if successful and the completion block isn't nil, run it 
    if (successBlock) { 
     // NB: if you do use a background queue, 
     // remember to dispatch the completion block to the main queue (not shown) 
     successBlock(brainImage) 
    } 

} 

然後,從您的視圖控制器,產生新的圖像,你可以更新您的圖像視圖:

[self.brain newImageWithSuccessBlock:^(UIImage *newImage) { 

    NSMutableArray *mutableImageArray; 
    if (self.imageView.animationImages) { 
     mutableImageArray = [self.imageView.animationImages mutableCopy]; 
    } else { 
     mutableImageArray = [NSMutableArray array]; 
    } 

    [mutableImageArray addObject:newImage]; 

    self.imageView.animationImages = [NSArray arrayWithArray:mutableImageArray]; 

}]; 
1

你可以試試這個代碼設置您的圖像陣列上的動畫

if(imageArray.count>0) 
{ 
    self.imageView.animationImages= imageArray; 
    self.imageView.animationDuration = 1/20; 
    self.imageView.animationRepeatCount =1; 
    [self.imageView startAnimating]; 
    [UIView beginAnimations:nil context:nil]; 
    [UIView setAnimationDuration:1.0]; 
    [UIView commitAnimations]; 
} 

我已經設置了th e動畫時間1/20根據FPS你可以設置你的動畫重複次數爲0永久重複