Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 圖片異步加載利器:Universal-Image-Loader 完整解析

編輯:關於 Android 程式設計

概述

專案地址:
https://github.com/nostra13/Android-Universal-Image-Loader

UIL(Universal-Image-Loader)是一款專為異步圖片加載、緩存與顯示而生的開源庫。這個既能異步加載又能自動緩存圖片的類,早已被廣大開發者採用,是 Android 生態中最常被使用的幾個開源庫之一。隨手反編譯幾個熱門 App,幾乎都能看到它的蹤影。

同類型的 Picasso 雖然 API 更為友善,卻在自訂能力上有所欠缺;而透過 UIL 的建構器,幾乎每一個環節都能自由配置。其中最关键的一點是:在抓取與緩存大型圖片時,Picasso 容易失敗,而 UIL 則表現得穩健許多。

主要特點

  • 多執行緒圖片加載(支援同步與非同步)
  • ImageLoader 配置高度自訂(執行緒池、下載器、解碼器、記憶體與磁碟緩存、顯示選項等)
  • 每次顯示圖片呼叫都能細粒度調整(佔位圖、緩存開關、解碼選項、Bitmap 處理與顯示等)
  • 記憶體與/或磁碟圖片緩存(可存放於裝置檔案系統或 SD 卡)
  • 加載過程監聽(包含下載進度)

簡單說明一下這個專案的結構:每一個圖片的加載與顯示任務都運行在獨立執行緒中,除非圖片已緩存在記憶體裡,那種情況下會立即顯示。若所需圖片緩存在本地,則會開啟獨立的執行緒佇列;若緩存中找不到對應圖片,任務執行緒便會從執行緒池中取得,因此快速顯示緩存圖片時不會有明顯卡頓。


由於源碼中無論是 loadImageSync 還是 loadImage,最終都會透過 displayImage 來加載,我們不妨一起看看它的整體流程:

準備工作

安裝

Maven:

  com.nostra13.universalimageloader universal-image-loader 1.9.3 

Gradle:

 compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.3'

加入網路與 SD 卡權限

由於加載過程需要透過網路獲取圖片,並且涉及緩存寫入,因此這兩個權限是必須的。

   

在首次使用前預先配置 Application 或 Activity

 // Create global configuration and initialize ImageLoader with this config ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this) ... .build(); ImageLoader.getInstance().init(config);

可接受的 URI 範例

 https://site.com/image.png // from Web file:///mnt/sdcard/image.png // from SD card file:///mnt/sdcard/video.mp4 // from SD card (video thumbnail) content://media/external/images/media/13 // from content provider content://media/external/video/media/13 // from content provider (video thumbnail) assets://image.png // from assets drawable:// + R.drawable.img // from drawables (non-9patch images)

NOTE: 只有在確實需要時才使用 drawable://。載入 drawable 時,請優先考慮原生做法 ImageView.setImageResource(...),而非透過 ImageLoader。

使用示例

 imageLoader.displayImage(imageUri, imageView); imageLoader.loadImage(imageUri, new SimpleImageLoadingListener() { @Override public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) { // Do whatever you want with Bitmap } }); // Load image, decode it to Bitmap and return Bitmap synchronously Bitmap bmp = imageLoader.loadImageSync(imageUri); // Load image, decode it to Bitmap and return Bitmap to callback ImageSize targetSize = new ImageSize(80, 50); // result Bitmap will be fit to this size imageLoader.loadImage(imageUri, targetSize, options, new SimpleImageLoadingListener() { @Override public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) { // Do whatever you want with Bitmap } }); // Load image, decode it to Bitmap and return Bitmap synchronously ImageSize targetSize = new ImageSize(80, 50); // result Bitmap will be fit to this size Bitmap bmp = imageLoader.loadImageSync(imageUri, targetSize, options);

此外,還可以透過 ImageLoadingProgressListener 來監聽加載進度。

配置說明

ImageLoaderConfiguration 應該作為 Application 級別的全域物件,只需配置一次。

 // DON'T COPY THIS CODE TO YOUR PROJECT! This is just example of ALL options using. // See the sample project how to use ImageLoader correctly. File cacheDir = StorageUtils.getCacheDirectory(context); ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context) .memoryCacheExtraOptions(480, 800) // default = device screen dimensions 推薦 .diskCacheExtraOptions(480, 800, null) //.推薦diskCacheExtraOptions(480, 800, null) .taskExecutor(...) .taskExecutorForCachedImages(...) .threadPoolSize(3) // default 推薦1-5 .threadPriority(Thread.NORM_PRIORITY - 2) // default .tasksProcessingOrder(QueueProcessingType.FIFO) // default .denyCacheImageMultipleSizesInMemory() //設置內存緩存不允許緩存一張圖片的多個尺寸,默認允許。 .memoryCache(new LruMemoryCache(2 * 1024 * 1024)) //使用強引用的緩存使用它,不過推薦使用weak與strong引用結合的UsingFreqLimitedMemoryCache或者使用全弱引用的WeakMemoryCache .memoryCacheSize(2 * 1024 * 1024) .memoryCacheSizePercentage(13) // default .diskCache(new UnlimitedDiscCache(cacheDir)) // default .diskCacheSize(50 * 1024 * 1024) .diskCacheFileCount(100) .diskCacheFileNameGenerator(new HashCodeFileNameGenerator()) // default .imageDownloader(new BaseImageDownloader(context)) // default .imageDecoder(new BaseImageDecoder()) // default .defaultDisplayImageOptions(DisplayImageOptions.createSimple()) // default .writeDebugLogs() .build();

自訂緩存目錄示例

 File cacheDir = StorageUtils.getOwnCacheDirectory(getApplicationContext(), imageloader/Cache); 
 .diskCache(new UnlimitedDiscCache(cacheDir))//自定義緩存路徑 

配置 Display Options

 // DON'T COPY THIS CODE TO YOUR PROJECT! This is just example of ALL options using. // See the sample project how to use ImageLoader correctly. DisplayImageOptions options = new DisplayImageOptions.Builder() .showImageOnLoading(R.drawable.ic_stub) // resource or drawable .showImageForEmptyUri(R.drawable.ic_empty) // resource or drawable .showImageOnFail(R.drawable.ic_error) // resource or drawable .resetViewBeforeLoading(false) // default .delayBeforeLoading(1000) .cacheInMemory(false) // default .cacheOnDisk(false) // default .preProcessor(...) .postProcessor(...) .extraForDownloader(...) .considerExifParams(false) // default .imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2) // default 推薦.imageScaleType(ImageScaleType.EXACTLY) 節省內存 .bitmapConfig(Bitmap.Config.ARGB_8888) // default 推薦.bitmapConfig(Bitmap.Config.RGB_565)節省內存 .decodingOptions(...) .displayer(new SimpleBitmapDisplayer()) // default //推薦使用RoundedBitmapDisplayer (Displays bitmap with rounded corners)和FadeInBitmapDisplayer (Displays image with fade in animation .handler(new Handler()) // default .build();

以上配置中的關鍵項說明:

1).imageScaleType(ImageScaleType imageScaleType) 用於設置圖片的縮放方式,可選類型有:

  • EXACTLY:圖像完全按比例縮小到目標大小
  • EXACTLY_STRETCHED:圖片拉伸到目標大小
  • IN_SAMPLE_INT:圖像以整數倍進行二次採樣
  • IN_SAMPLE_POWER_OF_2:圖片以 2 的倍數遞減,直到小於目標大小
  • NONE:不調整圖片大小

2).displayer(BitmapDisplayer displayer) 用於設置圖片的顯示方式:

  • RoundedBitmapDisplayer(int roundPixels):設置圓角圖片
  • FakeBitmapDisplayer():不做任何處理
  • FadeInBitmapDisplayer(int durationMillis):設置圖片漸顯時間
  • SimpleBitmapDisplayer():正常顯示圖片

需要注意的問題

1、緩存預設情況下並未啟用,需透過 DisplayImageOptions 手動開啟。

 // Create default options which will be used for every // displayImage(...) call if no options will be passed to this method DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder() ... .cacheInMemory(true) .cacheOnDisk(true) ... .build();ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext()) ... .defaultDisplayImageOptions(defaultOptions) ... .build();ImageLoader.getInstance().init(config); // Do it on Application start
 // Then later, when you want to display image ImageLoader.getInstance().displayImage(imageUrl, imageView); // Default options will be used

也可以在呼叫時直接傳入選項:

 DisplayImageOptions options = new DisplayImageOptions.Builder() ... .cacheInMemory(true) .cacheOnDisk(true) ... .build(); ImageLoader.getInstance().displayImage(imageUrl, imageView, options); // Incoming options will be used

2、為了避免 list(ListView、GridView 等)滾動時出現卡頓,可使用 PauseOnScrollListener。

 boolean pauseOnScroll = false; // or true boolean pauseOnFling = true; // or false PauseOnScrollListener listener = new PauseOnScrollListener(imageLoader, pauseOnScroll, pauseOnFling); listView.setOnScrollListener(listener);

幾點注意事項

1.上述兩個權限務必加入,否則會出錯。

2.ImageLoaderConfiguration 必須配置並在全域初始化 ImageLoader.getInstance().init(config),否則同樣會報錯。

3.ImageLoader 會依據 ImageView 的 height、width 來確定圖片顯示的寬高。

4.若經常出現 OOM(這一點值得特別留意),可嘗試:

①調小執行緒池大小(.threadPoolSize),建議 1-5;
②以 .bitmapConfig(Bitmap.config.RGB_565) 取代 ARGB_8888;
③採用 .imageScaleType(ImageScaleType.IN_SAMPLE_INT) 或 .imageScaleType(ImageScaleType.EXACTLY);
④避免使用 RoundedBitmapDisplayer,它會建立新的 ARGB_8888 格式 Bitmap 物件;
⑤使用 .memoryCache(new WeakMemoryCache()),而非 .cacheInMemory()。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved