Universalimageloader圖片載入框架快取本地圖片的使用
阿新 • • 發佈:2018-12-10
Universalimageloader圖片載入框架快取本地圖片的使用
首先需要新增依賴:
……………
在專案中建立一個自己的Application,編寫以下程式碼:
public class NewsApplication extends Application {
@Override public void onCreate() { super.onCreate(); //配置網路載入圖片的資訊 File cacheDir = new File(getExternalCacheDir() + "/image"); //設定快取位置 ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this) .diskCacheExtraOptions(480, 800, null) .denyCacheImageMultipleSizesInMemory() .memoryCache(new LruMemoryCache(2 * 1024 * 1024)) //設定快取大小 .memoryCacheSize(2 * 1024 * 1024) .diskCache(new UnlimitedDiskCache(cacheDir)) // default .diskCacheSize(50 * 1024 * 1024) .diskCacheFileCount(100) .diskCacheFileNameGenerator(new HashCodeFileNameGenerator()) // default .writeDebugLogs() .build(); ImageLoader.getInstance().init(config); }
下面在附上一個載入工具類,可直接使用:
public class ImageUtil {
private final ImageLoader mImageLoader; private DisplayImageOptions mOptions; private int mDefaultPicId = R.drawable.icon_default;//記錄每次設定的預設展示圖片 private static volatile ImageUtil sInstance; //UIL Volley(不推薦) Picasso Glide(雖然是基於Picasso,有一些特點:可以載入動圖gif,佔用空間小) //Fresco (facebook 包非常大,載入圖片比較專業 ,圖片消耗的資源比較大,容易OOM ) private ImageUtil(){ mImageLoader = ImageLoader.getInstance(); mOptions = new DisplayImageOptions.Builder() .showImageOnLoading(R.drawable.icon_default)// 載入的時候顯示的圖片 .showImageOnFail(R.drawable.icon_default) //失敗的時候載入 .resetViewBeforeLoading(false) // default .delayBeforeLoading(100) .cacheInMemory(true) // default .cacheOnDisk(true) // default .imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2) // default .bitmapConfig(Bitmap.Config.ARGB_8888) // default .build(); } public static ImageUtil getSingleton() { if (sInstance == null) { synchronized (ImageUtil.class) { if (sInstance == null) { sInstance = new ImageUtil(); } } } return sInstance; } public void display(String picUrl, ImageView imageView){ display(picUrl,imageView,R.drawable.icon_default); } public void display(String picUrl, ImageView imageView,int defaultPicId){ if(defaultPicId!=mDefaultPicId){ mDefaultPicId = defaultPicId;//記錄 mOptions = new DisplayImageOptions.Builder() .showImageOnLoading(defaultPicId) // resource or drawable .resetViewBeforeLoading(false) // default .delayBeforeLoading(100) .cacheInMemory(true) // default .cacheOnDisk(true) // default .imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2) // default .bitmapConfig(Bitmap.Config.ARGB_8888) // default .build(); } mImageLoader.displayImage(picUrl,imageView,mOptions); }
}