- 项目 gradle
ext{
image_loader_version = '1.9.5'
}
- 引入
api "com.nostra13.universalimageloader:universal-image-loader:$rootProject.image_loader_version"
- ImageLoaderHelper
object ImageLoaderHelper {
/**
* 初始化图片加载的选项
*
* @param context Context
* @param roundCornerRadius 圆角的半径(单位dp),默认为0
* @param defaultImageResId 加载出错时显示的图片
* @return DisplayImageOptions
*/
fun initImageOptions(context: Context, roundCornerRadius: Float = 0f, defaultImageResId: Int = R.mipmap.ic_launcher): DisplayImageOptions {
setImageLoaderCache(context)
val builder = DisplayImageOptions.Builder()
builder.showImageOnLoading(defaultImageResId)// 设置图片在下载期间显示的图片
.showImageForEmptyUri(defaultImageResId)// 设置图片URI为空或是错误的时候显示的图片
.showImageOnFail(defaultImageResId)// 设置图片加载错误时显示的图片
.cacheInMemory(true)// 设置下载的图片是否缓存在内存中
.cacheOnDisc(true)// 设置下载的图片是否缓存在SD卡中
if (roundCornerRadius > 0) {
builder.displayer(RoundedBitmapDisplayer(dp(context, roundCornerRadius)))
}
return builder.build()
}
/**
* 设置图片缓存的目录
*/
private fun setImageLoaderCache(context: Context) {
val cacheDir = StorageUtils.getOwnCacheDirectory(context, Values.PathAppCache_Root + Values.PathAppCache_ImageLoader)
// 配置ImageLoaderConfiguration
val configuration = ImageLoaderConfiguration.Builder(context)
.discCache(UnlimitedDiskCache(cacheDir))
.threadPoolSize(3)
.discCacheFileNameGenerator(Md5FileNameGenerator())
.writeDebugLogs()
.memoryCache(UsingFreqLimitedMemoryCache(2 * 1024 * 1024))// 内存缓存
.build()
ImageLoader.getInstance().init(configuration)// 全局初始化此配置
}
}
- 扩展函数
fun ImageView.show(context: Context, url: String, roundCornerRadius: Float = 0f, defaultImageResId: Int = R.mipmap.ic_launcher) {
ImageLoader.getInstance().displayImage(url, this, ImageLoaderHelper.initImageOptions(context, roundCornerRadius, defaultImageResId))
}
- 使用
iv_placeholder.show(this, "https://gitee.com/assets/my_wallet/banner2x.png")