ImageLoader配合ImageSwitcher的使用,imageloader使用

來源:互聯網
上載者:User

ImageLoader配合ImageSwitcher的使用,imageloader使用

先在MyApplication中初始化ImageLoader

initImageLoader(getApplicationContext());
   /**    * 初始化ImageLoader    * 如果你經常出現oom    * 減少配置的線程池的大小(.threadPoolSize(...)),建議1~5    * 配置中使用.diskCacheExtraOptions(480, 320, null)    * @param context    */    public static void initImageLoader(Context context) {        // This configuration tuning is custom. You can tune every option, you may tune some of them,         // or you can create default configuration by        // ImageLoaderConfiguration.createDefault(this);        // method.        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)                .threadPriority(Thread.NORM_PRIORITY - 1)                .threadPoolSize(5)                .denyCacheImageMultipleSizesInMemory()                .discCacheFileNameGenerator(new Md5FileNameGenerator())                .discCacheSize(100 * 1024 * 1024)                .tasksProcessingOrder(QueueProcessingType.LIFO)                //.enableLogging() // Not necessary in common                .build();        // Initialize ImageLoader with configuration.        MyImageLoader.getInstance().init(config);    }

 

 

再在BaseActivity中建立一個imageLoader 和設定參數

protected MyImageLoader imageLoader = MyImageLoader.getInstance();

 

/**     * 如果你經常出現oom     * 禁用在記憶體中緩衝cacheInMemory(false),     * 在顯示選項中使用 .bitmapConfig(Bitmap.Config.RGB_565) . RGB_565模式消耗的記憶體比ARGB_8888模式少兩倍.     * 配置中使用 .memoryCache(newWeakMemoryCache()) 或者完全禁用在記憶體中緩衝(don't call .cacheInMemory()).     * 在顯示選項中使用.imageScaleType(ImageScaleType.EXACTLY) 或 .imageScaleType(ImageScaleType.IN_SAMPLE_INT)     * 一定要對ImageLoaderConfiguration進行初始化,否則會報錯     * 開啟緩衝後預設會緩衝到外置SD卡如下地址(/sdcard/Android/data/[package_name]/cache).如果外置SD卡不存在,會緩衝到手機. 緩衝到Sd卡需要在AndroidManifest.xml檔案中進行配置WRITE_EXTERNAL_STORAGE     */    protected DisplayImageOptions options = new DisplayImageOptions.Builder()    //.resetViewBeforeLoading()    //.showImageOnLoading(R.drawable.ic_stub) //載入中顯示的圖片     //.showImageOnFail(R.drawable.ic_error)  //載入失敗顯示的圖片    //.cacheInMemory()    .cacheOnDisc()    // 設定下載的圖片是否緩衝在SD卡中   //緩衝在/mnt/shell/emulated/0/Android/data/com.sdmc.hotel.ollauncher/cache/uil-images    .imageScaleType(ImageScaleType.IN_SAMPLE_INT)//設定圖片以如何的編碼方式顯示(映像將被二次採樣的整數倍)    .bitmapConfig(Bitmap.Config.RGB_565)   //16 R佔5位 G佔6位 B佔5位 沒有透明度(A)    //.displayer(new FadeInBitmapDisplayer(500))//設定圖片漸顯的時間    .build();

 

 

在要使用的activity中使用方式

imageLoader.displayImage(this, path, (ImageView) mImageSwitcher.getCurrentView(),                         options, mImageLoadingListener);
imageLoader.loadImage(this, path,                         options, mImageLoadingListener);

還要加一個監聽器

    /**     * 把imageUri載入成bitmap之後就會觸動監聽,     * 然後把載入出來的bitmap加入到SparseArray<SoftReference<Bitmap>>     * before imageUri=file:///data/user/0/com.sdmc.hotel.ollauncher/files/cloud/public/upload/picture/1441178486.jpg     * after path=/public/upload/picture/1441178486.jpg;     * hashCode=-1524414597     */    private SimpleImageLoadingListener mImageLoadingListener = new SimpleImageLoadingListener() {                @Override        public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {            String path = imageUri.substring(imageUri.indexOf(Configs.getHotelProj(mContext))                     + Configs.getHotelProj(mContext).length());            log("before imageUri="+imageUri+"; getHotelProj"+Configs.getHotelProj(mContext));            log("after path="+path+";hashCode="+path.hashCode());            mLoadedImages.append(path.hashCode(), new SoftReference<Bitmap>(loadedImage));        }    };

以及一個軟引用的SparseArray

//SparseArray替代HashMap,SoftReference軟串連private SparseArray<SoftReference<Bitmap>> mLoadedImages = new SparseArray<SoftReference<Bitmap>>();

 

還有就是MyImageLoader 的類

/** * Copyright(c) 2003-2013 Shenzhen SDMC Technology Co.,LTD  * All Rights Reserved. *  * Filename : MyImageLoader.java * Author : wuxiaodi * Creation time : 下午2:01:58 - 2013-7-17 * Description : */package com.sdmc.hotel.util;import java.io.File;import android.content.Context;import android.widget.ImageView;import com.nostra13.universalimageloader.core.DisplayImageOptions;import com.nostra13.universalimageloader.core.ImageLoader;import com.nostra13.universalimageloader.core.assist.ImageLoadingListener;import com.nostra13.universalimageloader.core.assist.ImageSize;/** * Just to cache images in our archive, so to use it when off-line. */public class MyImageLoader extends ImageLoader {    private static MyImageLoader instance;        public static MyImageLoader getInstance() {        if (instance == null) {            synchronized (MyImageLoader.class) {                if (instance == null) {                    instance = new MyImageLoader();                }            }        }        return instance;    }        protected MyImageLoader() {            }        public void displayImage(Context context, String path, ImageView imageView) {        String furi = getLocalImage(context, path);        if (furi == null) {            super.displayImage(Configs.getServerAddress(context) + path, imageView);        } else {            super.displayImage(furi, imageView);        }    }        public void displayImage(Context context, String path, ImageView imageView, DisplayImageOptions options) {        String furi = getLocalImage(context, path);        if (furi == null) {            super.displayImage(Configs.getServerAddress(context) + path, imageView, options);        } else {            super.displayImage(furi, imageView, options);        }    }        public void displayImage(Context context, String path, ImageView imageView, ImageLoadingListener listener) {        String furi = getLocalImage(context, path);        if (furi == null) {            super.displayImage(Configs.getServerAddress(context) + path, imageView, listener);        } else {            super.displayImage(furi, imageView, listener);        }    }    /**     * displayImage()方法中,對ImageView對象使用的是Weak references,     * 方便記憶體回收行程回收ImageView對象,如果我們要載入固定大小的圖片的時候,     * 使用loadImage()方法需要傳遞一個ImageSize對象,而displayImage()方法會根據ImageView對象的     * 測量值,或者android:layout_width and android:layout_height設定的值,     * 或者android:maxWidth and/or android:maxHeight設定的值來裁剪圖片     * 根據控制項(ImageView)的大小對Bitmap進行裁剪,減少Bitmap佔用過多的記憶體     * @param context     * @param path     * @param imageView     * @param options     * @param listener     */    public void displayImage(Context context, String path, ImageView imageView, DisplayImageOptions options, ImageLoadingListener listener) {        String furi = getLocalImage(context, path);        if (furi == null) {//            log("furi1:"+Configs.getServerAddress(context) + path+";imageView"+imageView+";options"+options+";listener"+listener);            super.displayImage(Configs.getServerAddress(context) + path, imageView, options, listener);        } else {            //furi2:file:///data/data/com.sdmc.hotel.ollauncher/files/cloud/public/upload/picture/1441178355.jpg;imageViewandroid.widget.;optionscom.nostra13.;listenercom.sdmc//            log("furi2:"+furi+";imageView"+imageView+";options"+options+";listener"+listener);            super.displayImage(furi, imageView, options, listener);        }    }    /**     * displayImage更方便     * 使用ImageLoader的loadImage()方法來載入網狀圖片     * loadImage()是將圖片對象回調到ImageLoadingListener介面的onLoadingComplete()方法中,     * 需要我們手動去設定到ImageView上面     * @param context     * @param path     * @param listener     */    public void loadImage(Context context, String path, ImageLoadingListener listener) {        String furi = getLocalImage(context, path);        if (furi == null) {            super.loadImage(Configs.getServerAddress(context) + path, listener);        } else {            super.loadImage(furi, listener);        }    }    /**     * displayImage更方便     * 如果我們要指定圖片的大小該怎麼辦呢,這也好辦,初始化一個ImageSize對象,指定圖片的寬和高,代碼如下     * @param context     * @param path     * @param minImageSize  ImageSize mImageSize = new ImageSize(100, 100);       * @param listener     */    public void loadImage(Context context, String path, ImageSize minImageSize, ImageLoadingListener listener) {        String furi = getLocalImage(context, path);        if (furi == null) {            super.loadImage(Configs.getServerAddress(context) + path, minImageSize, listener);        } else {            super.loadImage(furi, minImageSize, listener);        }    }    public void loadImage(Context context, String path, DisplayImageOptions options, ImageLoadingListener listener) {        String furi = getLocalImage(context, path);        if (furi == null) {            super.loadImage(Configs.getServerAddress(context) + path, options, listener);        } else {            super.loadImage(furi, options, listener);        }    }    public void loadImage(Context context, String path, ImageSize targetImageSize, DisplayImageOptions options, ImageLoadingListener listener) {        String furi = getLocalImage(context, path);        if (furi == null) {            super.loadImage(Configs.getServerAddress(context) + path, targetImageSize, options, listener);        } else {            super.loadImage(furi, targetImageSize, options, listener);        }    }        private String getLocalImage(Context context, String path) {        File imagefile = new File(Configs.getCacheDir(context) + path);        if (imagefile.exists()) {            return "file://" + imagefile.getAbsolutePath();        } else {            return null;        }    }//    private void log(String msg) {//        LogUtil.info(this.getClass(), this + ":" + msg,"i");////    }}

 

 

 

 

 

 

 

 

 

如果要配合ImageSwitcher 的話也很方便,先建立一個ImageSwitcher 

private ImageSwitcher createImageSwitcher(JsonReader reader) {        ImageSwitcherLayoutParams params = new Gson().fromJson(reader,                ImageSwitcherLayoutParams.class);        mImageSwitcher = new ImageSwitcher(this);        mImageSwitcher.setFactory(this);        AlphaAnimation inAnim = new AlphaAnimation(0, 1);        inAnim.setDuration(300);        mImageSwitcher.setInAnimation(inAnim);        AlphaAnimation outAnim = new AlphaAnimation(1, 0);        outAnim.setDuration(400);        mImageSwitcher.setOutAnimation(outAnim);        AbsoluteLayout.LayoutParams lp = new AbsoluteLayout.LayoutParams(                params.width, params.height, params.x, params.y);        mImageSwitcher.setLayoutParams(lp);        return mImageSwitcher;    }

 

然後實現implements ViewFactory介面,重寫makeView方法

@Override    public View makeView() {        ImageView imageView = new ImageView(this);        imageView.setScaleType(ScaleType.FIT_XY);        imageView.setLayoutParams(new ImageSwitcher.LayoutParams(                ImageSwitcher.LayoutParams.MATCH_PARENT,                 ImageSwitcher.LayoutParams.MATCH_PARENT));        return imageView;    }

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.