1. 程式人生 > >(轉) Universal-Image-Loader使用大全(史上最屌)

(轉) Universal-Image-Loader使用大全(史上最屌)

pools 設置 raw 到你 eight cti option 項目目錄 proc

轉載自http://blog.csdn.net/zenjj11/article/details/38728481

項目介紹:
Android上最讓人頭疼的莫過於從網絡獲取圖片、顯示、回收,不論什麽一個環節有問題都可能直接OOM。這個項目也許能幫到你。Universal Image Loader for Android的目的是為了實現異步的網絡圖片載入、緩存及顯示,支持多線程異步載入

它最初來源於Fedor Vlasov的項目,且自此之後,經過大規模的重構和改進。
特性列舉:
多線程下載圖片,圖片能夠來源於網絡,文件系統,項目目錄assets中以及drawable中等
支持任意的配置ImageLoader。比如線程池,圖片下載器,內存緩存策略,硬盤緩存策略。圖片顯示選項以及其它的一些配置
支持圖片的內存緩存。文件系統緩存或者SD卡緩存
支持圖片下載過程的監聽
依據控件(ImageView)的大小對Bitmap進行裁剪,降低Bitmap占用過多的內存
較好的控制圖片的載入過程。比如暫停圖片載入,又一次開始載入圖片,一般使用在ListView,GridView中。滑動過程中暫停載入圖片,停止滑動的時候去載入圖片
提供在較慢的網絡下對圖片進行載入
使用過程:
創建默認的ImageLoader,全部的操作都由ImageLoader控制。該類使用單例設計模式,所以假設要獲取該類的實力。須要調用getInstance()方法。

在使用ImageLoader顯示圖片之前。你首先要初始化它的配置,調用ImageLoaderConfiguration的init()方法,然後你就能夠實現各種的顯示了。

//創建默認的ImageLoader配置參數

ImageLoaderConfiguration configuration = ImageLoaderConfiguration
.createDefault(this);
//Initialize ImageLoader with configuration.
ImageLoader.getInstance().init(configuration);

自己定義配置imageloader, 就像你已經知道的。首先,你須要使用ImageLoaderConfiguration對象來初始化ImageLoader。由於ImageLoader是單例。所以在程序開始的時候僅僅須要初始化一次就好了。建議你在Activity的onCreate()方法中初始化。假設一個ImageLoader已經初始化過。再次初始化不會有不論什麽效果。以下我們通過ImageLoaderConfiguration.Builder創建一個設置

File cacheDir =StorageUtils.getOwnCacheDirectory(this, "imageloader/Cache"
); ImageLoaderConfigurationconfig = new ImageLoaderConfiguration .Builder(this) .memoryCacheExtraOptions(480, 800) // maxwidth, max height,即保存的每一個緩存文件的最大長寬 .threadPoolSize(3)//線程池內載入的數量 .threadPriority(Thread.NORM_PRIORITY -2) .denyCacheImageMultipleSizesInMemory() .memoryCache(new UsingFreqLimitedMemoryCache(2* 1024 * 1024)) // You can pass your own memory cache implementation/你能夠通過自己的內存緩存實現 .memoryCacheSize(2 * 1024 * 1024) .discCacheSize(50 * 1024 * 1024) .discCacheFileNameGenerator(newMd5FileNameGenerator())//將保存的時候的URI名稱用MD5 加密 .tasksProcessingOrder(QueueProcessingType.LIFO) .discCacheFileCount(100) //緩存的文件數量 .discCache(new UnlimitedDiscCache(cacheDir))//自己定義緩存路徑 .defaultDisplayImageOptions(DisplayImageOptions.createSimple()) .imageDownloader(new BaseImageDownloader(this,5 * 1000, 30 * 1000)) // connectTimeout (5 s), readTimeout (30 s)超時時間 .writeDebugLogs() // Remove for releaseapp .build();//開始構建 ImageLoader.getInstance().init(config);

得到imageLoader

ImageLoader imageLoader imageLoader = ImageLoader.getInstance();  

使用過程:
(1)圖像操作是否參與緩存以及圖像效果的配置操作

DisplayImageOptions options = new DisplayImageOptions.Builder()  
          .showImageOnLoading(R.drawable.ic_stub)            //載入圖片時的圖片  
          .showImageForEmptyUri(R.drawable.ic_empty)         //沒有圖片資源時的默認圖片  
          .showImageOnFail(R.drawable.ic_error)              //載入失敗時的圖片  
          .cacheInMemory(true)                               //啟用內存緩存  
          .cacheOnDisk(true)                                 //啟用外存緩存  
          .considerExifParams(true)                          //啟用EXIF和JPEG圖像格式  
          .displayer(new RoundedBitmapDisplayer(20))         //設置顯示風格這裏是圓角矩形  
          .build();  

DisplayImageOptions以下是全部默認配置參數依據需求能夠自己定義配置

private int imageResOnLoading = 0;  
 private int imageResForEmptyUri = 0;  
 private int imageResOnFail = 0;  
 private Drawable imageOnLoading = null;  
 private Drawable imageForEmptyUri = null;  
 private Drawable imageOnFail = null;  
 private boolean resetViewBeforeLoading = false;  
 private boolean cacheInMemory = false;  
 private boolean cacheOnDisk = false;  
 private ImageScaleType imageScaleType = ImageScaleType.IN_SAMPLE_POWER_OF_2;  
 private Options decodingOptions = new Options();  
 private int delayBeforeLoading = 0;  
 private boolean considerExifParams = false;  
 private Object extraForDownloader = null;  
 private BitmapProcessor preProcessor = null;  
 private BitmapProcessor postProcessor = null;  
 private BitmapDisplayer displayer = DefaultConfigurationFactory.createBitmapDisplayer();  
 private Handler handler = null;  
 private boolean isSyncLoading = false;  

(2)圖片載入監聽器在這裏吧能夠設置載入時的動畫或者進度條之類的東西這裏

ImageLoadingListener animateFirstListener = new AnimateFirstDisplayListener();  
private static class AnimateFirstDisplayListener extends SimpleImageLoadingListener {  
        static final List<String> displayedImages = Collections.synchronizedList(new LinkedList<String>());  
         @Override  
         public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {  
              if (loadedImage != null) {  
                  ImageView imageView = (ImageView) view;  
                  boolean firstDisplay = !displayedImages.contains(imageUri);  
                  if (firstDisplay) {  
                       FadeInBitmapDisplayer.animate(imageView, 500);  
                       displayedImages.add(imageUri);  
                    }  
              }  
        }  
}  

(3)簡單設置就能夠給ImageView加入圖片了

imageLoader.displayImage(imageUrl, imageview, options, animateFirstListener);  

緩存的清理:
緩存的清理能夠按需求來定,能夠再每一個Activity的生命周期函數onDestroy中清理也能夠單獨設置讓用戶自行清理。

@Override
public void onDestroy() {
super.onDestroy();
imageLoader.clearMemoryCache();
imageLoader.clearDiskCache();
}

GirdView,ListView載入圖片:
相信大部分人都是使用GridView,ListView來顯示大量的圖片。而當我們高速滑動GridView,ListView。我們希望能停止圖片的載入,而在GridView,ListView停止滑動的時候載入當前界面的圖片。這個框架當然也提供這個功能,使用起來也非常easy,它提供了PauseOnScrollListener這個類來控制ListView,GridView滑動過程中停止去載入圖片,該類使用的是代理模式

listView.setOnScrollListener(new PauseOnScrollListener(imageLoader, pauseOnScroll, pauseOnFling));    
gridView.setOnScrollListener(new PauseOnScrollListener(imageLoader, pauseOnScroll, pauseOnFling));  

第一個參數就是我們的圖片載入對象ImageLoader, 第二個是控制是否在滑動過程中暫停載入圖片,假設須要暫停傳true即可了。第三個參數控制猛的滑動界面的時候圖片是否載入

OutOfMemoryError
盡管這個框架有非常好的緩存機制,有效的避免了OOM的產生,一般的情況下產生OOM的概率比較小。可是並不能保證OutOfMemoryError永遠不發生,這個框架對於OutOfMemoryError做了簡單的catch,保證我們的程序遇到OOM而不被crash掉,可是假設我們使用該框架常常發生OOM。我們應該怎麽去改善呢?

  1. 降低線程池中線程的個數,在ImageLoaderConfiguration中threadPoolSize中配置,推薦配置1-5
  2. 在DisplayImageOptions選項中配置bitmapConfigBitmap.Config.RGB_565,由於默認是ARGB_8888, 使用RGB_565會比使用ARGB_8888少消耗2倍的內存
  3. 在ImageLoaderConfiguration中配置圖片的內存緩存為memoryCache(newWeakMemoryCache()) 或者不使用內存緩存
  4. 在DisplayImageOptions選項中設置ImageScale.imageScaleType(ImageScaleType.IN_SAMPLE_INT)或者imageScaleType(ImageScaleType.EXACTLY)

通過上面這些,相信大家對Universal-Image-Loader框架的使用已經非常的了解了,我們在使用該框架的時候盡量的使用displayImage()方法去載入圖片。loadImage()是將圖片對象回調到ImageLoadingListener接口的onLoadingComplete()方法中,須要我們手動去設置到ImageView上面。displayImage()方法中,對ImageView對象使用的是Weak references,方便垃圾回收器回收ImageView對象。假設我們要載入固定大小的圖片的時候,使用loadImage()方法須要傳遞一個ImageSize對象。而displayImage()方法會依據ImageView對象的測量值。或者android:layout_width and android:layout_height設定的值,或者android:maxWidth and/or android:maxHeight設定的值來裁剪圖片

希望能大家對圖片的載入有到幫助,如有補充,敬請提出,我會更新在後面,謝謝

(轉) Universal-Image-Loader使用大全(史上最屌)