1、Android常用的图片加载框架有很多,最早的图片流,imageloader,随着手机硬件的发展,出现了功能更强大的图片加载框架;现在项目中我基本上都会选择使用Glide图片加载框架;
介绍这个框架前先分别对下这几个框架的优缺点吧
Picasso,Glide,Fresco的前世今生
基本项对比
对比项 Picasso Glide Fresco
地址 https://github.com/square/picasso https://github.com/bumptech/glide https://github.com/facebook/fresco
发布时间 2013年5月 2014年9月 2015年5月
是否支持gif false true true
是否支持webP true true true
视频缩略图 false true true
大小 100k 500 KB 2~3M
加载速度 中 高 高
DiskCache true true true
Easy of use low mediun difficult
开发者 Square主导 Google主导 Facebook主导
2、既然选择推荐Glide,那就说下Glide的优点吧
a 多种图片格式的缓存,适用于更多的内容表现形式(如Gif、WebP、缩略图、Video)
b 生命周期集成(根据Activity或者Fragment的生命周期管理图片加载请求)
c 高效处理Bitmap(bitmap的复用和主动回收,减少系统回收压力)
d 高效的缓存策略,灵活(Picasso只会缓存原始尺寸的图片,Glide缓存的是多种规格),加载速度快且内存开销小(默认Bitmap格式的不同,使得内存开销是Picasso的一半)
3、使用方法
(1) 在app的build.gradle中添加引用
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
implementation 'com.github.bumptech.glide:glide:4.9.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.9.0'
}
(2)在项目的Build.gradle中添加引用
repositories {
mavenCentral()
google()
jcenter()
}
(3)开始Glide的使用方法
Glide 使用简明的流式语法API,这是一个非常棒的设计,因为它允许你在大部分情况下一行代码搞定需求:
Glide.with(上下文对象)
.load(url)
.into(imageView);
4.6版本后通过RequestOption设置属性
RequestOptions options = new RequestOptions()
.placeholder(R.mipmap.icon) //加载成功之前占位图
.error(R.mipmap.ic_launcher) //加载错误之后的错误图
.override(100,100) //指定图片的尺寸
.fitCenter() //指定图片的缩放类型为fitCenter (等比例缩放图片,宽或者是高等于
ImageView的宽或者是高。是指其中一个满足即可不会一定imageview)
.centerCrop()//指定图片的缩放类型为centerCrop (等比例缩放图片,直到图片的宽高都
大于等于ImageView的宽度,然后截取中间的显示。)
.skipMemoryCache(true) //不使用内存缓存
.diskCacheStrategy(DiskCacheStrategy.ALL) //缓存所有版本的图像
.diskCacheStrategy(DiskCacheStrategy.NONE) //不使用硬盘本地缓存
.diskCacheStrategy(DiskCacheStrategy.DATA) //只缓存原来分辨率的图片
.diskCacheStrategy(DiskCacheStrategy.RESOURCE); //只缓存最终的图片