目录
1.Glide的基本使用
1. 介绍
Glide是一个快速高效的Android图片加载库,可以自动加载网络、本地文件,app资源中的图片,注重于平滑的滚动。
开源地址:GitHub - bumptech/glide: An image loading and caching library for Android focused on smooth scrolling 中文文档:Glide v4 : 快速高效的Android图片加载库
引入Glide:
implementation 'com.github.bumptech.glide:glide:4.11.0' annotationProcessor 'com.github.bumptech.glide:compiler:4.11.0'
基本使用: Glide.with([fragment/Context/View]) .load(url) .into(imageView)
2. Glide占位符
Glide4中占位图的使用方法,包括(placeholder, error,fallback)三种占位图
-
placeholder 正在请求图片的时候展示的图片
-
error 如果请求失败的时候展示的图片 (如果没有设置,还是展示placeholder的占位符)
-
fallback 如果请求的url/model为 null 的时候展示的图片 (如果没有设置,还是展示placeholder的占位符)
示例
RequestOptions requestOptions = new RequestOptions() .placeholder(R.drawable.hold) .error(R.drawable.error) .fallback(R.drawable.empty) .override(100,100); Glide.with(this) .load("https://i.328888.xyz/2023/02/20/X1nsd.jpeg1") .apply(requestOptions) .into(imageView);
2.Glide的进阶使用
1. 过渡动画
定义 Glide 如何从占位符到新加载的图片,或从缩略图到全尺寸图像过渡。
Glide默认是Drawable 此时用DrawableTransitionOptions
如果使用了.asBitmap()方法 此时需要对应使用BitmapTransitionOptions
withCrossFade() 传int就是过渡动画显示的ms数 传DrawableCrossFadeFactory就是自定义工厂 可用于避免占位图显示
交叉淡入(避免占位图还能显示)
示例
//自定义工厂使用 DrawableCrossFadeFactory factory = new DrawableCrossFadeFactory.Builder().setCrossFadeEnabled(true).build(); Glide.with(this) .load("https://i.328888.xyz/2023/02/20/X1nsd.jpeg") .apply(requestOptions) .transition(DrawableTransitionOptions.withCrossFade(factory)) .into(imageView);
注意:
为了提升性能,请在使用 Glide 向 ListView , GridView, 或 RecyclerView 加载图片时考虑避免使用动画。
2. 变化 transform()
获取资源并修改它,然后返回被修改后的资源。通常变换操作是用来完成剪裁或对位图应用过滤器。比如对图片 进行圆角配置。
Glide.with(this) .load(URL) .transform(...) .into(iv);
-
CircleCrop:圆角
-
RoundedCorners: 四个角度统一指定
-
GranularRoundedCorners:四个角度单独指定
-
Rotate:旋转
3. Generated API
1、添加 Glide注解处理器的依赖:
annotationProcessor 'com.github.bumptech.glide:compiler:4.11.0'
2、在 Application 模块中包含一个 AppGlideModule 的实现
@GlideModule public class MyAppModule extends AppGlideModule { }
此时我们能够更简单的完成占位符等配置:
GlideApp.with(this).load("") .placeholder(R.drawable.hold) .into(imageView);
4. GlideExtension与GlideOption
定义一个在频繁使用的选项集合。
@GlideExtension public class MyAppExtension { private MyAppExtension() { } // utility class @GlideOption public static BaseRequestOptions<?> defaultImg(BaseRequestOptions<?> options) { return options.placeholder(R.drawable.hold) .error(R.drawable.error) .fallback(R.drawable.error); } }
使用(加一个defaultImg()方法即可)
GlideApp.with(this).load("") .placeholder(R.drawable.hold) .defaultImg() .into(imageView);