目前我們看到的漸進式加載主要有三種實現方式:
1)依次從網絡加載不同尺寸的圖片,由小到大。最開始先拉取一張小縮略圖做拉伸顯示,然後拉取中等規格的圖並覆蓋顯示,最後拉取原圖,完成後呈現清晰的原圖。
2)直接從網絡拉取最大的圖片,每接收到一點數據就顯示一點,從而實現從模糊到清晰、從上到下逐步刷新的效果。
3)結合前兩種:先拉取縮略圖做拉伸顯示,再用第二種方式直接拉取原圖,兼顧漸進加載的視覺效果與減少中間網絡請求的優勢。
ImageIO 的官方指南中這樣描述:"If you have a very large image, or are loading image data over the web, you may want to create an incremental image source so that you can draw the image data as you accumulate it." 意思是:如果你想加載一張特別大的圖片,或者從網絡加載圖片,可以通過創建一個增量式 image source 來實現邊累積數據、邊繪製圖片的漸進加載效果。
以前做 PowerCam 時,為了在 iOS 上處理超大圖(一張 10000×8000 分辨率的中國地圖),也曾嘗試這種方式,結果整幅圖加載到內存後內存吃不消而被迫放棄。現在想來,對於這種超大圖,其實可以採用「分片」處理的方式,每次只處理一小塊,這裡就留給大家思考。
本文重點討論如何用 CGImageSource 實現從網絡端漸進加載圖片。要達到這個目的,我們需要創建一個 NSURLConnection 並實現其代理,在每次接收到數據時更新圖片即可。主要實現源碼如下:
#import "SvIncrementallyImage.h"
#import <ImageIO/ImageIO.h>
#import <CoreFoundation/CoreFoundation.h>
@interface SvIncrementallyImage () {
NSURLRequest *_request;
NSURLConnection *_conn;
CGImageSourceRef _incrementallyImgSource;
NSMutableData *_recieveData;
long long _expectedLeght;
bool _isLoadFinished;
}
@property (nonatomic, retain) UIImage *image;
@end
@implementation SvIncrementallyImage
- (id)initWithURL:(NSURL *)imageURL {
self = [super init];
if (self) {
_imageURL = [imageURL retain];
_request = [[NSURLRequest alloc] initWithURL:_imageURL];
_conn = [[NSURLConnection alloc] initWithRequest:_request delegate:self];
_incrementallyImgSource = CGImageSourceCreateIncremental(NULL);
_recieveData = [[NSMutableData alloc] init];
_isLoadFinished = false;
}
return self;
}
#pragma mark - NSURLConnectionDataDelegate
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
_expectedLeght = response.expectedContentLength;
NSString *mimeType = response.MIMEType;
NSArray *arr = [mimeType componentsSeparatedByString:@"/"];
if (arr.count < 1 || ![[arr objectAtIndex:0] isEqual:@"image"]) {
NSLog(@"not a image url");
[connection cancel];
_conn = nil;
}
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(@"Connection %@ error, error info: %@", connection, error);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
// 若數據尚未完整,生成最終圖片
if (!_isLoadFinished) {
CGImageSourceUpdateData(_incrementallyImgSource, (CFDataRef)_recieveData, _isLoadFinished);
CGImageRef imageRef = CGImageSourceCreateImageAtIndex(_incrementallyImgSource, 0, NULL);
self.image = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);
}
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[_recieveData appendData:data];
_isLoadFinished = false;
if (_expectedLeght == _recieveData.length) {
_isLoadFinished = true;
}
CGImageSourceUpdateData(_incrementallyImgSource, (CFDataRef)_recieveData, _isLoadFinished);
CGImageRef imageRef = CGImageSourceCreateImageAtIndex(_incrementallyImgSource, 0, NULL);
self.image = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);
}
@end
從程式碼中不難看出整體流程:先根據傳入的 URL 創建一個 NSURLConnection,同時創建一個空的 CGImageSource;之後每次收到數據時調用 CGImageSourceUpdateData 更新數據源,再調用 CGImageSourceCreateImageAtIndex 獲取最新的圖片即可。
看似簡單的背後,我們也應該理解它的原理。文件都是有格式的,一般文件頭部記錄了一些關於格式的元數據,後面才是真正的數據。以最簡單的 BMP 圖片為例,其結構大致分為四部分:
1)BITMAPFILEHEADER:記錄文件大小,以及實際圖像數據距文件頭的距離;
2)BITMAPINFOHEADER:記錄圖片的寬、高、位深等信息;
3)可選的調色板信息;
4)最後是真正的圖像數據。
前三部分信息很小,加起來通常不超過 100 字節。一旦拿到這些頭部信息,我們就能根據後續數據逐步構建圖片;隨着數據越來越完整,構建出的圖片也越來越清晰,直至全部加載完成。BMP 是簡單的圖片格式,JPG、PNG 雖然結構更複雜,但總體構成思路類似。ImageIO 正是幫我們完成了眾多圖片格式的編解碼,並一步步構造出最終圖像——這也正是漸進式加載得以實現的底層原理。