Android第三方图片加载库Universal Image Loader

主页: https://github.com/nostra13/Android-Universal-Image-Loader

特性:

  • 多线程图片加载(同步/异步)
  • 可自由定制图片加载方式(thread executors, downloader, decoder, memory and disk cache, display image options, etc.)
  • 可自由定制图片显示方式(stub images, caching switch, decoding options, Bitmap processing and displaying, etc)
  • 图片缓存的处理(内存缓存 / 硬盘缓存(本机 / SD卡))
  • 监听图片加载进度

工作流程
这里写图片描述

常用方法

显示图片

ImageLoader.getInstance().loadImage(String uri, ImageLoadingListener listener)  
//SimpleImageLoadingListener是ImageLoadingListener的空实现

displayImage(String uri, ImageView imageView)

displayImage(String uri, ImageView imageView, DisplayImageOptions options)

displayImage(String uri, ImageView imageView, DisplayImageOptions options,
ImageLoadingListener listener, ImageLoadingProgressListener progressListener) 

加载其他图片

// 图片来自本机文件
String imageUrl = ImageDownloader.Scheme.FILE.wrap("/mnt/sdcard/image.png");
// 图片来自Content Provider
String contentURL = ImageDownloader.Scheme.CONTENT.wrap("/media/external/audio/albumart/13");
//图片来源于assets
String assetsUrl = ImageDownloader.Scheme.ASSETS.wrap("image.png");
//图片来源于drawable
String drawableUrl = ImageDownloader.Scheme.DRAWABLE.wrap("R.drawable.image");

可处理的URI类型

"http://site.com/image.png" // 网络地址
"file:///mnt/sdcard/image.png" // SD卡
"file:///mnt/sdcard/video.mp4" // SD卡 (视频缩略图)
"content://media/external/images/media/13" // content provider
"content://media/external/video/media/13" // content provider (视频缩略图)
"assets://image.png" // assets资源
"drawable://" + R.drawable.img // drawables资源 (不包含.9图)

使用步骤:

  • 1.添加依赖
compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.4'
  • 2.添加权限
    如需要请求网络图片,添加
<uses-permission android:name="android.permission.INTERNET" />

如需要SD卡缓存,添加

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 
  • 3.初始化配置 , 在调用UIL前必须初始化配置
ImageLoaderConfiguration configuration = ImageLoaderConfiguration.createDefault(this);  
ImageLoader.getInstance().init(configuration); 

注意事项:

  • 1.默认情况UIL是没有缓存功能的 , 所以需要在构造DisplayImageOptions时打开缓存功能 .cacheInMemory(), .cacheOnDisk()

  • 2.如果要缓存图片到本地硬盘 , 不要忘记添加SD卡读写权限

  • 3.如果发生OOM异常,参考如下处理

    • 缩小线程池的大小, ImageLoaderConfiguration. threadPoolSize() , 推荐值为1-5
    • 指定图片质量时,使用RGB_565, DisplayImageOptions. bitmapConfig(Bitmap.Config.RGB_565)
    • 推荐使用DisplayImageOptions.imageScaleType(ImageScaleType.EXACTLY)
    • 使用diskCacheExtraOptions时,推荐参数为ImageLoaderConfiguration.diskCacheExtraOptions(480, 320, null)
  • 4.UIL已实现的内存缓存配置类.用于ImageLoaderConfiguration memoryCache()
    仅强引用 LruMemoryCache

强引用 + 弱引用
UsingFreqLimitedMemoryCache
LRULimitedMemoryCache
FIFOLimitedMemoryCache
LargestLimitedMemoryCache
LimitedAgeMemoryCache

仅弱引用 WeakMemoryCache

  • 5.UIL已实现的硬盘缓存配置类,用于ImageLoaderConfiguration diskCache()
    UnlimitedDiscCache (默认值)
    LruDiskCache
    LimitedAgeDiscCache

  • 6.UIL已实现的图片显示类, 用于DisplayImageOptions displayer()
    RoundedBitmapDisplayer (圆角图片) 使用该属性时,ImageView必须指定宽高
    FadeInBitmapDisplayer (渐显图片)

  • 7.为了避免在可滚动视图中(ListView / GridView)发生OOM异常,请使用PauseOnScrollListener , 如

boolean pauseOnScroll = false; // or true
boolean pauseOnFling = true; // or false
PauseOnScrollListener listener = new PauseOnScrollListener(imageLoader, pauseOnScroll, pauseOnFling);
listView.setOnScrollListener(listener);

Configuration 参数详解

File cacheDir = StorageUtils.getCacheDirectory(context); // 自定义缓存文件夹
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
        .memoryCacheExtraOptions(480, 800) // 指定缓存到内存时图片的大小,默认是屏幕尺寸的长宽
        .diskCacheExtraOptions(480, 800, null) // 指定缓存到硬盘时图片的大小,并不建议使用
        .taskExecutor(new Executor()) // 自定义一个线程来加载和显示图片
        .taskExecutorForCachedImages(new Executor())// 自定义一个线程来缓存图片
        .threadPoolSize(3) // default, 指定线程池大小
        .threadPriority(Thread.NORM_PRIORITY - 2) // default ,指定线程优先级 
        .tasksProcessingOrder(QueueProcessingType.FIFO) // default , 指定加载显示图片的任务队列的类型
        .denyCacheImageMultipleSizesInMemory() // 禁止在内存中缓存同一张图片的多个尺寸类型
        .memoryCache(new LruMemoryCache(2 * 1024 * 1024)) // 指定内存缓存的大小,默认值为1/8 应用的最大可用内存
        .memoryCacheSize(2 * 1024 * 1024) 
        .memoryCacheSizePercentage(13) // default
        .diskCache(new UnlimitedDiskCache(cacheDir)) // default , 指定硬盘缓存的地址
        .diskCacheSize(50 * 1024 * 1024) // 指定硬盘缓存的大小
        .diskCacheFileCount(100) // 指定硬盘缓存的文件个数
        .diskCacheFileNameGenerator(new HashCodeFileNameGenerator()) // default , 指定硬盘缓存时文件名的生成器
        .imageDownloader(new BaseImageDownloader(context)) // default , 指定图片下载器
        .imageDecoder(new BaseImageDecoder()) // default , 指定图片解码器
        .defaultDisplayImageOptions(DisplayImageOptions.createSimple()) // default , 指定图片显示的配置
        .writeDebugLogs() // 是否显示Log
        .build();

Display Options 参数详解

DisplayImageOptions options = new DisplayImageOptions.Builder()
        .showImageOnLoading(R.drawable.ic_stub) // 图片正在加载时显示的图片资源ID
        .showImageForEmptyUri(R.drawable.ic_empty) // URI为空时显示的图片资源ID
        .showImageOnFail(R.drawable.ic_error) // 图片加载失败时显示的图片资源ID
        .resetViewBeforeLoading(false)  // default 图片在下载前是否重置,复位
        .delayBeforeLoading(1000) // 图片开始加载前的延时.默认是0
        .cacheInMemory(false) // default , 是否缓存在内存中, 默认不缓存
        .cacheOnDisk(false) // default , 是否缓存在硬盘 , 默认不缓存
        .preProcessor(new BitmapProcessor) // 设置图片缓存在内存前的图片处理器
        .postProcessor(new BitmapProcessor) // 设置图片在缓存到内存以后 , 显示在界面之前的图片处理器
        .extraForDownloader(...) // 为图片下载设置辅助参数
        .considerExifParams(false) // default , 设置是否考虑JPEG图片的EXIF参数信息,默认不考虑
        .imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2) // default , 指定图片缩放的方式,ListView/GridView/Gallery推荐使用此默认值
        .bitmapConfig(Bitmap.Config.ARGB_8888) // default , 指定图片的质量,默认是 ARGB_8888
        .decodingOptions(...) // 指定图片的解码方式
        .displayer(new SimpleBitmapDisplayer()) // default , 设置图片显示的方式,用于自定义
        .handler(new Handler()) // default ,设置图片显示的方式和ImageLoadingListener的监听, 用于自定义
        .build();

示例

1.添加依赖和添加权限
build.gradle文件中

compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.4'

AndroidManifest.xml文件中

<!-- Include following permission if you load images from Internet -->
<uses-permission android:name="android.permission.INTERNET"/>
<!-- Include following permission if you want to cache images on SD card -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

2.java代码

2.1简单的写法

//简单的写法
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this).build();
ImageLoader.getInstance().init(config);

ImageLoader imageLoader = ImageLoader.getInstance();
imageLoader.displayImage(URL, imageView);

2.2使用Application初始化ImageLoaderConfiguration和使用自定义Activity父类初始化DisplayImageOptions

用Application统一管理config,避免重复创建

1.创建Application子类,设置config的各项属性

public class MyApp extends Application {
    @Override
    public void onCreate() {
        super.onCreate();

        File cacheDir = StorageUtils.getCacheDirectory(this); // 自定义缓存文件夹
        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this)
                .memoryCacheExtraOptions(480, 800) // 指定缓存到内存时图片的大小,默认是屏幕尺寸的长宽
//                .diskCacheExtraOptions(480, 800, null) // 指定缓存到硬盘时图片的大小,并不建议使用
//                .taskExecutor(new Executor()) // 自定义一个线程来加载和显示图片
//                .taskExecutorForCachedImages(new Executor())// 自定义一个线程来缓存图片
                .threadPoolSize(3) // default, 指定线程池大小
                .threadPriority(Thread.NORM_PRIORITY - 2) // default ,指定线程优先级
                .tasksProcessingOrder(QueueProcessingType.FIFO) // default , 指定加载显示图片的任务队列的类型
                .denyCacheImageMultipleSizesInMemory() // 禁止在内存中缓存同一张图片的多个尺寸类型
                .memoryCache(new LruMemoryCache(2 * 1024 * 1024)) // 指定内存缓存的大小,默认值为1/8 应用的最大可用内存
                .memoryCacheSize(2 * 1024 * 1024)
                .memoryCacheSizePercentage(13) // default
//                .diskCache(new UnlimitedDiskCache(cacheDir)) // default , 指定硬盘缓存的地址
                .diskCacheSize(50 * 1024 * 1024) // 指定硬盘缓存的大小
                .diskCacheFileCount(100) // 指定硬盘缓存的文件个数
                .diskCacheFileNameGenerator(new HashCodeFileNameGenerator()) // default , 指定硬盘缓存时文件名的生成器
                .imageDownloader(new BaseImageDownloader(this)) // default , 指定图片下载器
//                .imageDecoder(new BaseImageDecoder()) // default , 指定图片解码器
                .defaultDisplayImageOptions(DisplayImageOptions.createSimple()) // default , 指定图片显示的配置
                .writeDebugLogs() // 是否显示Log
                .build();

        ImageLoader.getInstance().init(config);
    }
}

2.AndroidManifest.xml中指明application

<application
        android:name=".MyApp"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <!-- ... -->
</application>

3.创建BaseActivity继承自Activity,初始化options各项设置

public class BaseActivity extends Activity {
    public DisplayImageOptions options;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        options = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.mipmap.ic_launcher) // 图片正在加载时显示的图片资源ID
                .showImageForEmptyUri(R.mipmap.ic_launcher) // URI为空时显示的图片资源ID
                .showImageOnFail(R.mipmap.ic_launcher) // 图片加载失败时显示的图片资源ID
                .resetViewBeforeLoading(false)  // default 图片在下载前是否重置,复位
                .delayBeforeLoading(1000) // 图片开始加载前的延时.默认是0
                .cacheInMemory(false) // default , 是否缓存在内存中, 默认不缓存
                .cacheOnDisk(false) // default , 是否缓存在硬盘 , 默认不缓存
//                .preProcessor(new BitmapProcessor) // 设置图片缓存在内存前的图片处理器
//                .postProcessor(new BitmapProcessor) // 设置图片在缓存到内存以后 , 显示在界面之前的图片处理器
//                .extraForDownloader(...) // 为图片下载设置辅助参数
                .considerExifParams(false) // default , 设置是否考虑JPEG图片的EXIF参数信息,默认不考虑
                .imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2) // default , 指定图片缩放的方式,ListView/GridView/Gallery推荐使用此默认值
                .bitmapConfig(Bitmap.Config.ARGB_8888) // default , 指定图片的质量,默认是 ARGB_8888
//                .decodingOptions(...) // 指定图片的解码方式
                .displayer(new SimpleBitmapDisplayer()) // default , 设置图片显示的方式,用于自定义
//                .handler(new Handler()) // default ,设置图片显示的方式和ImageLoadingListener的监听, 用于自定义
                .build();
    }
}

4.MainActivity继承BaseActivity,具体图片加载

public class MainActivity extends BaseActivity {

    private static final String URL = "http://p2.so.qhimg.com/t0146fac2d27cc2b0ac.jpg";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        imageView = (ImageView) findViewById(R.id.imageView);

        ImageLoader.getInstance().displayImage(URL, imageView, options);//options --> 可以直接用父类变量
    }
}
发布了60 篇原创文章 · 获赞 22 · 访问量 9万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章