圖片加載框架簡單介紹<一> ImageLoader 的基本使用

  • **ImageLoader簡單介紹 **
    ImageLoader 是最早開源的 Android 圖片緩存庫, 強(qiáng)大的緩存機(jī)制, 早期使用這個(gè)圖片加載框架的Android應(yīng)用非常多句喜, 至今仍然有不少 Android 開發(fā)者在使用贝次。

  • 使用第一步岖赋,配置一些參數(shù)

DisplayImageOptions options = new DisplayImageOptions.Builder().showStubImage(R.drawable.ic_stub) // 設(shè)置圖片下載期間顯示的圖片
        .showImageOnLoading(R.drawable.ic_empty)    //設(shè)置下載過程中圖片顯示   
        .showImageForEmptyUri(R.drawable.ic_empty) // 設(shè)置圖片Uri為空或是錯(cuò)誤的時(shí)候顯示的圖片
        .showImageOnFail(R.drawable.ic_error) // 設(shè)置圖片加載或解碼過程中發(fā)生錯(cuò)誤顯示的圖片
        .cacheInMemory(true) // 設(shè)置下載的圖片是否緩存在內(nèi)存中
        .cacheOnDisc(true) // 設(shè)置下載的圖片是否緩存在SD卡中
        .build(); // 創(chuàng)建配置過得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);   

因?yàn)镮mageLoader使用的是單例模式谒主。所以上面的這些配置(還有一些其他配置選項(xiàng)英妓,這里就不一一寫出來了)赔嚎,在項(xiàng)目中只需要設(shè)置一次就可以了。

  • 第二步转锈,獲取ImageLoader圖片加載框架實(shí)例對象
ImageLoader imageLoader = ImageLoader.getInstance(); 

到這里就可以使用獲取到的imagerLoader來進(jìn)行圖片加載了盘寡,使用imagerLoader加載圖片有很多種方式,簡單說三種最常用的撮慨,然后再把全部加在方法源碼貼在后面竿痰,根據(jù)自己的不同需求,大家再具體使用相應(yīng)的方法砌溺。

  • 根據(jù)url把圖片展示到imageView控件上(異步加載)
imageLoader.displayImage(imageUri, imageView); 
  • 根據(jù)url把圖片展示到imageView控件上影涉,并監(jiān)聽圖片加載是否完畢(異步加載)
imageLoader.displayImage(imageUrl, imageView, null , new SimpleImageLoadingListener(){

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

}, new ImageLoadingProgressListener(){

    @Override
    public void onProgressUpdate(String imageUri, View view, int current, int total) {
        //在這里執(zhí)行你想要做的事情,total總進(jìn)度规伐,current當(dāng)前加載進(jìn)度
    }
});

上面代碼中僅僅重寫了監(jiān)聽對象SimpleImageLoadingListener的onLoadingComplete方法蟹倾,其實(shí)還有其他三個(gè)方法:onLoadingStarted(加載開始),onLoadingFailed(加載失敗)鲜棠,onLoadingCancelled(加載取消)肌厨,可以根據(jù)自己的具體需要去考慮是否進(jìn)行重寫。

  • 根據(jù)url獲取到圖片文件并返回為位圖格式對象(同步加載)
Bitmap bmp = imageLoader.loadImageSync(imageUri);
  • 以下代碼為ImageLoader對象加載圖片的三大類方法及其重載
    方法loadImage是異步加載豁陆,一般需要對加載過程設(shè)置監(jiān)聽柑爸,待圖片資源加載完畢,再手動(dòng)操作把圖片展示到控件上盒音。
    方法displayImage是異步加載表鳍,可以不設(shè)置監(jiān)聽,待圖片資源加載完畢祥诽,會自動(dòng)把圖片展示到控件上譬圣。
    方法loadImageSync是同步加載,待圖片資源加載完畢雄坪,直接返回位圖資源對象
    //ImageViewAware這個(gè)類主要是將ImageView進(jìn)行一個(gè)包裝胁镐,將  ImageView的強(qiáng)引用變成弱引用,
    //當(dāng)內(nèi)存不足的時(shí)候诸衔,可以更好的回收ImageView對象盯漂,還有就是獲取ImageView的寬度和高度。
    //這使得我們可以根據(jù)ImageView的寬高去對圖片進(jìn)行一個(gè)裁剪笨农,減少內(nèi)存的使用就缆。
    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進(jìn)行封裝

    建議大家在使用框架的時(shí)候,自己再進(jìn)行一下二次封裝谒亦,這樣如果以后換框架竭宰,整個(gè)項(xiàng)目改動(dòng)的地方會非常少,而且自己封裝的東西份招,用起來肯定會更加得心應(yīng)手切揭。下面是我自己對ImageLoader進(jìn)行簡單封裝生成的一個(gè)類,大家可以參考下然后自己封裝一個(gè)最好锁摔。

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)//設(shè)置下載的圖片是否緩存在內(nèi)存
        .cacheOnDisk(true)//設(shè)置下載的圖片是否緩存在SD卡中
        .showImageOnLoading(resourceId)         // 設(shè)置圖片下載期間顯示的圖片  
        .showImageForEmptyUri(resourceId)  // 設(shè)置圖片Uri為空或是錯(cuò)誤的時(shí)候顯示的圖片  
        .showImageOnFail(resourceId)       // 設(shè)置圖片加載或解碼過程中發(fā)生錯(cuò)誤顯示的圖片  
        .build();
        imageLoader.displayImage(imageUrl, imageView, tempOptions);
    }

    public void displayMyImage(String imageUrl, ImageView imageView, int resourceId, SimpleImageLoadingListener listener) {
        DisplayImageOptions tempOptions = new DisplayImageOptions.Builder()
                .cacheInMemory(false)//設(shè)置下載的圖片是否緩存在內(nèi)存
                .cacheOnDisk(true)//設(shè)置下載的圖片是否緩存在SD卡中
                .showImageOnLoading(resourceId)         // 設(shè)置圖片下載期間顯示的圖片
                .showImageForEmptyUri(resourceId)  // 設(shè)置圖片Uri為空或是錯(cuò)誤的時(shí)候顯示的圖片
                .showImageOnFail(resourceId)       // 設(shè)置圖片加載或解碼過程中發(fā)生錯(cuò)誤顯示的圖片
                .build();
        imageLoader.displayImage(imageUrl, imageView, tempOptions, listener);
    }

    public void initImageLoader() {
        
        DisplayImageOptions options = new DisplayImageOptions.Builder().showStubImage(R.drawable.ic_stub) // 設(shè)置圖片下載期間顯示的圖片
                .showImageOnLoading(R.drawable.ic_empty)    //設(shè)置下載過程中圖片顯示   
                .showImageForEmptyUri(R.drawable.ic_empty) // 設(shè)置圖片Uri為空或是錯(cuò)誤的時(shí)候顯示的圖片
                .showImageOnFail(R.drawable.ic_error) // 設(shè)置圖片加載或解碼過程中發(fā)生錯(cuò)誤顯示的圖片
                .cacheInMemory(true) // 設(shè)置下載的圖片是否緩存在內(nèi)存中
                .cacheOnDisc(true) // 設(shè)置下載的圖片是否緩存在SD卡中
                .build(); // 創(chuàng)建配置過得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);   
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末廓旬,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子谐腰,更是在濱河造成了極大的恐慌孕豹,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,542評論 6 504
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件十气,死亡現(xiàn)場離奇詭異励背,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)砸西,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,822評論 3 394
  • 文/潘曉璐 我一進(jìn)店門叶眉,熙熙樓的掌柜王于貴愁眉苦臉地迎上來址儒,“玉大人,你說我怎么就攤上這事衅疙×ぃ” “怎么了?”我有些...
    開封第一講書人閱讀 163,912評論 0 354
  • 文/不壞的土叔 我叫張陵炼蛤,是天一觀的道長妖爷。 經(jīng)常有香客問我蝶涩,道長理朋,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,449評論 1 293
  • 正文 為了忘掉前任绿聘,我火速辦了婚禮嗽上,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘熄攘。我一直安慰自己兽愤,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,500評論 6 392
  • 文/花漫 我一把揭開白布挪圾。 她就那樣靜靜地躺著浅萧,像睡著了一般。 火紅的嫁衣襯著肌膚如雪哲思。 梳的紋絲不亂的頭發(fā)上洼畅,一...
    開封第一講書人閱讀 51,370評論 1 302
  • 那天,我揣著相機(jī)與錄音棚赔,去河邊找鬼帝簇。 笑死,一個(gè)胖子當(dāng)著我的面吹牛靠益,可吹牛的內(nèi)容都是我干的丧肴。 我是一名探鬼主播,決...
    沈念sama閱讀 40,193評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼胧后,長吁一口氣:“原來是場噩夢啊……” “哼芋浮!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起壳快,我...
    開封第一講書人閱讀 39,074評論 0 276
  • 序言:老撾萬榮一對情侶失蹤途样,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后濒憋,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體何暇,經(jīng)...
    沈念sama閱讀 45,505評論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,722評論 3 335
  • 正文 我和宋清朗相戀三年凛驮,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了裆站。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,841評論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖宏胯,靈堂內(nèi)的尸體忽然破棺而出羽嫡,到底是詐尸還是另有隱情,我是刑警寧澤肩袍,帶...
    沈念sama閱讀 35,569評論 5 345
  • 正文 年R本政府宣布杭棵,位于F島的核電站,受9級特大地震影響氛赐,放射性物質(zhì)發(fā)生泄漏魂爪。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,168評論 3 328
  • 文/蒙蒙 一艰管、第九天 我趴在偏房一處隱蔽的房頂上張望滓侍。 院中可真熱鬧,春花似錦牲芋、人聲如沸撩笆。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,783評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽夕冲。三九已至,卻和暖如春裂逐,著一層夾襖步出監(jiān)牢的瞬間歹鱼,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,918評論 1 269
  • 我被黑心中介騙來泰國打工絮姆, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留醉冤,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 47,962評論 2 370
  • 正文 我出身青樓篙悯,卻偏偏與公主長得像蚁阳,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個(gè)殘疾皇子鸽照,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,781評論 2 354

推薦閱讀更多精彩內(nèi)容

  • 一螺捐、簡歷準(zhǔn)備 1、個(gè)人技能 (1)自定義控件矮燎、UI設(shè)計(jì)定血、常用動(dòng)畫特效 自定義控件 ①為什么要自定義控件? Andr...
    lucas777閱讀 5,202評論 2 54
  • Volley框架 Volley是Google官方出的一套小而巧的異步請求庫诞外,該框架封裝的擴(kuò)展性很強(qiáng)澜沟,支持HttpC...
    void_Zhao閱讀 10,702評論 2 2
  • 7.1 壓縮圖片 一、基礎(chǔ)知識 1峡谊、圖片的格式 jpg:最常見的圖片格式茫虽。色彩還原度比較好刊苍,可以支持適當(dāng)壓縮后保持...
    AndroidMaster閱讀 2,515評論 0 13
  • title: 第12章 Bitmap的加載和Cachetags: []notebook: Android開發(fā)藝術(shù)探...
    反復(fù)橫跳的龍?zhí)?/span>閱讀 1,766評論 0 10
  • 1.什么領(lǐng)帶使男性看起來性感、有活力呢濒析?(提示:“性感”總統(tǒng)克林頓曾用它在美國贏取了無數(shù)女選民的青睞) 2.人人想...
    IngridWu閱讀 304評論 0 0