我正在開發一個帶有圖庫的應用程序。 所有圖像都在設備光盤(文檔目錄)上,但無法順利顯示。與UIImageView性能不佳(本地圖像)
由於某些圖片很大(2000px * 2000px),我在後臺線程中加載它們,縮小它們並將它們顯示在主線程中。
這裏是我的UIImageView擴展:
@implementation UIImageView (BackgroundResize)
- (void)localImageFromPath: (NSString *) path scaledTo: (CGSize) size {
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0);
dispatch_async(queue, ^{
//Load image
NSData * imgData = [[NSData alloc] initWithContentsOfFile:path];
UIImage * original = [[[UIImage alloc] initWithData:imgData] autorelease];
[imgData release];
CGSize imgSize = original.size;
float widthScale = size.width/imgSize.width;
float heightScale = size.height/imgSize.height;
float scaleFactor = widthScale;
if (heightScale < scaleFactor) {
scaleFactor = heightScale;
}
UIImage * result = nil;
//Scale if necessary
if (scaleFactor < 1.0) {
result = [[UIImage alloc] initWithCGImage:original.CGImage scale:1/scaleFactor orientation:original.imageOrientation];
} else {
result = [original retain];
}
NSLog(@"Image prepeared on backgroud thread, update ui image on main..");
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"Begin updating image on main thread");
self.image = result;
[result release];
[[NSNotificationCenter defaultCenter] postNotificationName:NTF_IMG_LOADED object:self];
NSLog(@"Updated");
});
});
dispatch_release(queue);
}
@end
在控制檯輸出似乎一切都完美,所有的調試字符串顯示,在不到1秒(6個非常大的圖像),但是UI被阻止並顯示圖像延遲10秒。
在iOS上顯示大型本地圖像的正確方法是什麼?
應用是建立的iOS5 + ..
感謝,
爲什麼要發佈'result'?您是否檢查通知何時到達? – 2013-04-06 17:07:12
我們不使用ARC,結果是幾行保留/分配,所以我必須釋放它。 通知在圖像實際顯示前10秒即刻到達。 – miham 2013-04-06 17:35:32