一、Inage-Loader特性: 1、支持多线程下载图片,图片可以来源于网络,文件系统,项目文件夹assets中以及drawable中等 2、支持自定义的配置,例如线程池,图片下载器,内存缓存策略,硬盘缓存策略,图片显示选项等等 3、支持图片的内存缓存,文件系统缓存或者SD卡缓存 4、支持图片下载过程的监听 5、根据控件(ImageView)的大小对Bitmap进行裁剪,减少Bitmap占用过多的内存 6、较好的控制图片的加载过程,例如暂停图片加载,重新开始加载图片,一般使用在ListView,GridView中,滑动过程中暂停加载图片,停止滑动的时候去加载图片 7、提供在较慢的网络下对图片进行加载 二、使用方法: 1、创建ImageLoader,所有的操作都由ImageLoader控制。该类使用单例设计模式,所以如果要获取该类的实例,需要调用getInstance()方法。在使用ImageLoader显示图片之前,你首先要初始化它的配置,调用ImageLoaderConfiguration的init()方法,ok了。
//创建ImageLoader ImageLoaderConfiguration config = ImageLoaderConfiguration .createDefault(mContext); ImageLoader.getInstance().init(config);// 全局初始化此配置2、自定义配置,首先,需要使用ImageLoaderConfiguration对象来初始化ImageLoader。由于ImageLoader是单例,所以在程序开始的时候只需要初始化一次就好了。建议你在Baseapplication的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);3、创建ImageLoader
ImageLoader imageLoader imageLoader = ImageLoader.getInstance();4、缓存及图像设置
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();5.1、监听
imageLoader.loadImage(imageUrl, options, new ImageLoadingListener() { @Override public void onLoadingStarted(String s, View view) { } @Override public void onLoadingFailed(String s, View view, FailReason failReason) { } @Override public void onLoadingComplete(String s, View view, Bitmap bitmap) { } @Override public void onLoadingCancelled(String s, View view) { } });5.2、添加图片
imageLoader.displayImage(imageUrl, imageview, options, animateFirstListener);6、清理缓存:
imageLoader.clearMemoryCache(); imageLoader.clearDiskCache();新闻热点
疑难解答