2011-02-27 42 views
2

在我的視圖控制器中,如何知道某個UIImageView何時完成加載(文檔目錄中的大jpeg)?我需要知道,以便我可以使用此高分辨率圖像視圖交換佔位符低分辨率圖像視圖。我是否需要創建一個自定義回調來了解這一點?任何方式都可以。如何知道UIimageView何時完成加載?

順便說一句,這裏是一個代碼片段,我加載圖像:

NSString *fileName = [NSString stringWithFormat:@"hires_%i.jpg", currentPage]; 
NSString *filePath = [NSString stringWithFormat:@"%@/BookImage/%@", [self documentsDirectory], fileName]; 
hiResImageView.image = [[[UIImage alloc] initWithContentsOfFile:filePath] autorelease]; 
+0

請提供您的源代碼如何加載圖像。 – Tim 2011-02-27 11:38:05

+0

謝謝@Tim - 這裏有一些源代碼。 – m0rtimer 2011-02-27 11:41:06

+0

'大jpeg'有多大?因爲如果你說的話真的很大,那麼使用某種平鋪就會好得多。涉及UIImageViews和大圖像有很大的性能影響。 – lxt 2011-02-27 13:23:12

回答

2

的UIImageView是沒有做任何加載在所有。所有的加載都由[[UIImage alloc] initWithContentsOfFile:filePath]完成,並且在文件加載時線程被阻塞(所以在調用最終返回時加載已經完成)。

你想要做的是這樣的:

- (void)loadImage:(NSString *)filePath { 
    [self performSelectorInBackground:@selector(loadImageInBackground:) withObject:filePath]; 
} 

- (void)loadImageInBackground:(NSString *)filePath { 
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; 
    UIImage *image = [[UIImage alloc] initWithContentsOfFile:filePath]; 
    [self performSelectorOnMainThread:@selector(didLoadImageInBackground:) withObject:image waitUntilDone:YES]; 
    [image release]; 
    [pool release]; 
} 

- (void)didLoadImageInBackground:(UIImage *)image { 
    self.imageView.image = image; 
} 

你將建立self.imageView顯示低清晰度的圖像,然後調用loadImage:加載高分辨率版本。

請注意,如果您在didLoadImageInBackground:從以前的調用中被調用之前重複調用此函數,則可能導致設備內存不足。或者您可能會讓第一次調用的圖像比第二次調用花費的時間長得多,而第二次調用的圖像在調用第一次調用之前被調用第二次調用。解決這些問題留給讀者(或另一個問題)。

+0

謝謝,很好的回答。但是,是 - (void)didLoadImageInBackground:(UIImage *)圖像保證等到圖像加載完成後?這是我關心的問題,即運行時任務的實際排序。 – m0rtimer 2011-02-28 04:50:06

+0

正如我前面所說的,圖像在'[[UIImage alloc] initWithContentsOfFile:filePath]'返回時完成加載。 – Anomie 2011-02-28 04:55:28

+0

這個,我明白 - 謝謝。 – m0rtimer 2011-02-28 09:21:56