1. 程式人生 > >圖片載入框架簡單介紹 ImageLoader 的基本使用

圖片載入框架簡單介紹 ImageLoader 的基本使用

  • ImageLoader簡單介紹
    ImageLoader 是最早開源的 Android 圖片快取庫, 強大的快取機制, 早期使用這個圖片載入框架的Android應用非常多, 至今仍然有不少 Android 開發者在使用。

  • 使用第一步,配置一些引數

DisplayImageOptions options = new DisplayImageOptions.Builder().showStubImage(R.drawable.ic_stub) // 設定圖片下載期間顯示的圖片
        .showImageOnLoading(R.drawable.ic_empty)    //設定下載過程中圖片顯示   
.showImageForEmptyUri(R.drawable.ic_empty) // 設定圖片Uri為空或是錯誤的時候顯示的圖片 .showImageOnFail(R.drawable.ic_error) // 設定圖片載入或解碼過程中發生錯誤顯示的圖片 .cacheInMemory(true) // 設定下載的圖片是否快取在記憶體中 .cacheOnDisc(true) // 設定下載的圖片是否快取在SD卡中 .build(); // 建立配置過得DisplayImageOption物件 ImageLoaderConfiguration config = new
ImageLoaderConfiguration .Builder( context.getApplicationContext()) .defaultDisplayImageOptions(options) .threadPriority(Thread.NORM_PRIORITY - 2) .denyCacheImageMultipleSizesInMemory() .discCacheFileNameGenerator(new Md5FileNameGenerator()) .tasksProcessingOrder(QueueProcessingType.LIFO) .build(); imageLoader = ImageLoader.getInstance(); imageLoader.init(config);

因為ImageLoader使用的是單例模式。所以上面的這些配置(還有一些其他配置選項,這裡就不一一寫出來了),在專案中只需要設定一次就可以了。

  • 第二步,獲取ImageLoader圖片載入框架例項物件
ImageLoader imageLoader = ImageLoader.getInstance(); 

到這裡就可以使用獲取到的imagerLoader來進行圖片載入了,使用imagerLoader載入圖片有很多種方式,簡單說三種最常用的,然後再把全部加在方法原始碼貼在後面,根據自己的不同需求,大家再具體使用相應的方法。

  • 根據url把圖片展示到imageView控制元件上(非同步載入)
imageLoader.displayImage(imageUri, imageView); 
  • 根據url把圖片展示到imageView控制元件上,並監聽圖片載入是否完畢(非同步載入)
imageLoader.displayImage(imageUrl, imageView, null , new SimpleImageLoadingListener(){

    @Override
    public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
        //在這裡執行你想要做的事情
    }

}, new ImageLoadingProgressListener(){

    @Override
    public void onProgressUpdate(String imageUri, View view, int current, int total) {
        //在這裡執行你想要做的事情,total總進度,current當前載入進度
    }
});

上面程式碼中僅僅重寫了監聽物件SimpleImageLoadingListener的onLoadingComplete方法,其實還有其他三個方法:onLoadingStarted(載入開始),onLoadingFailed(載入失敗),onLoadingCancelled(載入取消),可以根據自己的具體需要去考慮是否進行重寫。

  • 根據url獲取到圖片檔案並返回為點陣圖格式物件(同步載入)
Bitmap bmp = imageLoader.loadImageSync(imageUri);
  • 以下程式碼為ImageLoader物件載入圖片的三大類方法及其過載
    方法loadImage是非同步載入,一般需要對載入過程設定監聽,待圖片資源載入完畢,再手動操作把圖片展示到控制元件上。
    方法displayImage是非同步載入,可以不設定監聽,待圖片資源載入完畢,會自動把圖片展示到控制元件上。
    方法loadImageSync是同步載入,待圖片資源載入完畢,直接返回點陣圖資源物件
    //ImageViewAware這個類主要是將ImageView進行一個包裝,將  ImageView的強引用變成弱引用,
    //當記憶體不足的時候,可以更好的回收ImageView物件,還有就是獲取ImageView的寬度和高度。
    //這使得我們可以根據ImageView的寬高去對圖片進行一個裁剪,減少記憶體的使用。
    public void displayImage(String uri, ImageAware imageAware) {
        this.displayImage(uri, (ImageAware)imageAware, (DisplayImageOptions)null, (ImageLoadingListener)null, (ImageLoadingProgressListener)null);
    }

    public void displayImage(String uri, ImageAware imageAware, ImageLoadingListener listener) {
        this.displayImage(uri, (ImageAware)imageAware, (DisplayImageOptions)null, listener, (ImageLoadingProgressListener)null);
    }

    public void displayImage(String uri, ImageAware imageAware, DisplayImageOptions options) {
        this.displayImage(uri, (ImageAware)imageAware, options, (ImageLoadingListener)null, (ImageLoadingProgressListener)null);
    }

    public void displayImage(String uri, ImageAware imageAware, DisplayImageOptions options, ImageLoadingListener listener) {
        this.displayImage(uri, (ImageAware)imageAware, options, listener, (ImageLoadingProgressListener)null);
    }

    public void displayImage(String uri, ImageAware imageAware, DisplayImageOptions options, ImageLoadingListener listener, ImageLoadingProgressListener progressListener) {
        this.checkConfiguration();
        if(imageAware == null) {
            throw new IllegalArgumentException("Wrong arguments were passed to displayImage() method (ImageView reference must not be null)");
        } else {
            if(listener == null) {
                listener = this.emptyListener;
            }

            if(options == null) {
                options = this.configuration.defaultDisplayImageOptions;
            }

            if(TextUtils.isEmpty(uri)) {
                this.engine.cancelDisplayTaskFor(imageAware);
                listener.onLoadingStarted(uri, imageAware.getWrappedView());
                if(options.shouldShowImageForEmptyUri()) {
                    imageAware.setImageDrawable(options.getImageForEmptyUri(this.configuration.resources));
                } else {
                    imageAware.setImageDrawable((Drawable)null);
                }

                listener.onLoadingComplete(uri, imageAware.getWrappedView(), (Bitmap)null);
            } else {
                ImageSize targetSize = ImageSizeUtils.defineTargetSizeForView(imageAware, this.configuration.getMaxImageSize());
                String memoryCacheKey = MemoryCacheUtils.generateKey(uri, targetSize);
                this.engine.prepareDisplayTaskFor(imageAware, memoryCacheKey);
                listener.onLoadingStarted(uri, imageAware.getWrappedView());
                Bitmap bmp = (Bitmap)this.configuration.memoryCache.get(memoryCacheKey);
                ImageLoadingInfo imageLoadingInfo;
                if(bmp != null && !bmp.isRecycled()) {
                    L.d("Load image from memory cache [%s]", new Object[]{memoryCacheKey});
                    if(options.shouldPostProcess()) {
                        imageLoadingInfo = new ImageLoadingInfo(uri, imageAware, targetSize, memoryCacheKey, options, listener, progressListener, this.engine.getLockForUri(uri));
                        ProcessAndDisplayImageTask displayTask1 = new ProcessAndDisplayImageTask(this.engine, bmp, imageLoadingInfo, defineHandler(options));
                        if(options.isSyncLoading()) {
                            displayTask1.run();
                        } else {
                            this.engine.submit(displayTask1);
                        }
                    } else {
                        options.getDisplayer().display(bmp, imageAware, LoadedFrom.MEMORY_CACHE);
                        listener.onLoadingComplete(uri, imageAware.getWrappedView(), bmp);
                    }
                } else {
                    if(options.shouldShowImageOnLoading()) {
                        imageAware.setImageDrawable(options.getImageOnLoading(this.configuration.resources));
                    } else if(options.isResetViewBeforeLoading()) {
                        imageAware.setImageDrawable((Drawable)null);
                    }

                    imageLoadingInfo = new ImageLoadingInfo(uri, imageAware, targetSize, memoryCacheKey, options, listener, progressListener, this.engine.getLockForUri(uri));
                    LoadAndDisplayImageTask displayTask = new LoadAndDisplayImageTask(this.engine, imageLoadingInfo, defineHandler(options));
                    if(options.isSyncLoading()) {
                        displayTask.run();
                    } else {
                        this.engine.submit(displayTask);
                    }
                }

            }
        }
    }

    public void displayImage(String uri, ImageView imageView) {
        this.displayImage(uri, (ImageAware)(new ImageViewAware(imageView)), (DisplayImageOptions)null, (ImageLoadingListener)null, (ImageLoadingProgressListener)null);
    }

    public void displayImage(String uri, ImageView imageView, DisplayImageOptions options) {
        this.displayImage(uri, (ImageAware)(new ImageViewAware(imageView)), options, (ImageLoadingListener)null, (ImageLoadingProgressListener)null);
    }

    public void displayImage(String uri, ImageView imageView, ImageLoadingListener listener) {
        this.displayImage(uri, (ImageAware)(new ImageViewAware(imageView)), (DisplayImageOptions)null, listener, (ImageLoadingProgressListener)null);
    }

    public void displayImage(String uri, ImageView imageView, DisplayImageOptions options, ImageLoadingListener listener) {
        this.displayImage(uri, (ImageView)imageView, options, listener, (ImageLoadingProgressListener)null);
    }

    public void displayImage(String uri, ImageView imageView, DisplayImageOptions options, ImageLoadingListener listener, ImageLoadingProgressListener progressListener) {
        this.displayImage(uri, (ImageAware)(new ImageViewAware(imageView)), options, listener, progressListener);
    }

    public void loadImage(String uri, ImageLoadingListener listener) {
        this.loadImage(uri, (ImageSize)null, (DisplayImageOptions)null, listener, (ImageLoadingProgressListener)null);
    }

    public void loadImage(String uri, ImageSize targetImageSize, ImageLoadingListener listener) {
        this.loadImage(uri, targetImageSize, (DisplayImageOptions)null, listener, (ImageLoadingProgressListener)null);
    }

    public void loadImage(String uri, DisplayImageOptions options, ImageLoadingListener listener) {
        this.loadImage(uri, (ImageSize)null, options, listener, (ImageLoadingProgressListener)null);
    }

    public void loadImage(String uri, ImageSize targetImageSize, DisplayImageOptions options, ImageLoadingListener listener) {
        this.loadImage(uri, targetImageSize, options, listener, (ImageLoadingProgressListener)null);
    }

    public void loadImage(String uri, ImageSize targetImageSize, DisplayImageOptions options, ImageLoadingListener listener, ImageLoadingProgressListener progressListener) {
        this.checkConfiguration();
        if(targetImageSize == null) {
            targetImageSize = this.configuration.getMaxImageSize();
        }

        if(options == null) {
            options = this.configuration.defaultDisplayImageOptions;
        }

        NonViewAware imageAware = new NonViewAware(uri, targetImageSize, ViewScaleType.CROP);
        this.displayImage(uri, (ImageAware)imageAware, options, listener, progressListener);
    }

    public Bitmap loadImageSync(String uri) {
        return this.loadImageSync(uri, (ImageSize)null, (DisplayImageOptions)null);
    }

    public Bitmap loadImageSync(String uri, DisplayImageOptions options) {
        return this.loadImageSync(uri, (ImageSize)null, options);
    }

    public Bitmap loadImageSync(String uri, ImageSize targetImageSize) {
        return this.loadImageSync(uri, targetImageSize, (DisplayImageOptions)null);
    }

    public Bitmap loadImageSync(String uri, ImageSize targetImageSize, DisplayImageOptions options) {
        if(options == null) {
            options = this.configuration.defaultDisplayImageOptions;
        }

        options = (new Builder()).cloneFrom(options).syncLoading(true).build();
        ImageLoader.SyncImageLoadingListener listener = new ImageLoader.SyncImageLoadingListener();
        this.loadImage(uri, targetImageSize, options, listener);
        return listener.getLoadedBitmap();
    }
  • 對ImageLoader進行封裝

    建議大家在使用框架的時候,自己再進行一下二次封裝,這樣如果以後換框架,整個專案改動的地方會非常少,而且自己封裝的東西,用起來肯定會更加得心應手。下面是我自己對ImageLoader進行簡單封裝生成的一個類,大家可以參考下然後自己封裝一個最好。

public class ImagerLoaderUtil {

    private ImageLoader imageLoader;
    private DisplayImageOptions options;
    private Context context;
    private static ImagerLoaderUtil imagerLoaderUtil;

    private ImagerLoaderUtil(Context context) {
        super();
        this.context = context;
    }

    public synchronized static ImagerLoaderUtil getInstance(Context context){
        if(imagerLoaderUtil == null){
            imagerLoaderUtil = new ImagerLoaderUtil(context);
            imagerLoaderUtil.initImageLoader();
        }
        return imagerLoaderUtil;
    }

    public void displayMyImage(String imageUrl, ImageView imageView ){
        imageLoader.displayImage(imageUrl, imageView);
    }

    public void displayMyImage(String imageUrl, ImageView imageView,SimpleImageLoadingListener listener ){
        imageLoader.displayImage(imageUrl, imageView, listener);
    }

    public void displayMyImage(String imageUrl, ImageView imageView, int resourceId){
        DisplayImageOptions tempOptions = new DisplayImageOptions.Builder()
        .cacheInMemory(false)//設定下載的圖片是否快取在記憶體
        .cacheOnDisk(true)//設定下載的圖片是否快取在SD卡中
        .showImageOnLoading(resourceId)         // 設定圖片下載期間顯示的圖片  
        .showImageForEmptyUri(resourceId)  // 設定圖片Uri為空或是錯誤的時候顯示的圖片  
        .showImageOnFail(resourceId)       // 設定圖片載入或解碼過程中發生錯誤顯示的圖片  
        .build();
        imageLoader.displayImage(imageUrl, imageView, tempOptions);
    }

    public void displayMyImage(String imageUrl, ImageView imageView, int resourceId, SimpleImageLoadingListener listener) {
        DisplayImageOptions tempOptions = new DisplayImageOptions.Builder()
                .cacheInMemory(false)//設定下載的圖片是否快取在記憶體
                .cacheOnDisk(true)//設定下載的圖片是否快取在SD卡中
                .showImageOnLoading(resourceId)         // 設定圖片下載期間顯示的圖片
                .showImageForEmptyUri(resourceId)  // 設定圖片Uri為空或是錯誤的時候顯示的圖片
                .showImageOnFail(resourceId)       // 設定圖片載入或解碼過程中發生錯誤顯示的圖片
                .build();
        imageLoader.displayImage(imageUrl, imageView, tempOptions, listener);
    }

    public void initImageLoader() {

        DisplayImageOptions options = new DisplayImageOptions.Builder().showStubImage(R.drawable.ic_stub) // 設定圖片下載期間顯示的圖片
                .showImageOnLoading(R.drawable.ic_empty)    //設定下載過程中圖片顯示   
                .showImageForEmptyUri(R.drawable.ic_empty) // 設定圖片Uri為空或是錯誤的時候顯示的圖片
                .showImageOnFail(R.drawable.ic_error) // 設定圖片載入或解碼過程中發生錯誤顯示的圖片
                .cacheInMemory(true) // 設定下載的圖片是否快取在記憶體中
                .cacheOnDisc(true) // 設定下載的圖片是否快取在SD卡中
                .build(); // 建立配置過得DisplayImageOption物件

        ImageLoaderConfiguration config = new ImageLoaderConfiguration
                .Builder(
                context.getApplicationContext())
                .defaultDisplayImageOptions(options)
                .threadPriority(Thread.NORM_PRIORITY - 2)
                .denyCacheImageMultipleSizesInMemory()
                .discCacheFileNameGenerator(new Md5FileNameGenerator())
                .tasksProcessingOrder(QueueProcessingType.LIFO)
                .build();
                imageLoader = ImageLoader.getInstance();
                imageLoader.init(config);   
    }
}
  • 最後附上ImagerLoader在gitHub上面的專案地址:點選開啟