實際開發過程中,容易碰到從網絡上獲取圖片尺寸的場景,比如一個UIImageView要裝載從網絡上獲取的圖片,但要先設置其frame,此時又不知道圖片尺寸,就要從網絡上獲取尺寸了。為了最好的用戶體驗,一般最好由服務器返回圖片尺寸參數。
但因特殊原因,服務器無法提供的,就需要自己先將圖片下載到本地,再從本地獲取圖片尺寸了。但問題在於,圖片下載是是耗時操作,等圖片下載完成后,在拿到圖片的尺寸設置控件的frame,這樣雖然解決了尺寸的問題,但會讓界面看起來非常卡。為了解決這個問題,我們可以開啟子線程,異步獲取圖片。(主線程繼續加載UI控件,子線程下載圖片),等子線程下載完畢后,再回到主線程中刷新UI。也可以在圖片沒有下載下來前使用一個本地的占位圖片去代替。
1 2 // 創建串行隊列 3 dispatch_queue_t queue = dispatch_queue_create("cn.xxx.queue", DISPATCH_QUEUE_SERIAL); 4 5 [prodetailUrl enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { 6 7 8 // 開啟異步函數,獲取下載圖片,獲取尺寸 9 dispatch_async(queue, ^{ 10 NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:obj]]; 11 UIImage *image = [UIImage imageWithData:data]; 12 CGSize imgSize = [image getSize]; 13 [weakSelf.DetialImgHeigths addObject:@(imgSize.height)]; 14 [weakSelf.DetialImgWides addObject:@(imgSize.width)]; 15 16 // 回到主線程執行 17 dispatch_sync(dispatch_get_main_queue(), ^(){ 18 19 [weakSelf.tb reloadData]; 20 [weakSelf.detailtb reloadData]; 21 }); 22 });24 }];