在 Android 中,ImageView 从 Android 9.0(API 级别 28) 开始原生支持 GIF 动画,通过 AnimatedImageDrawable 类实现。在之前的版本中,ImageView 并不支持直接播放 GIF 动画,只能显示 GIF 的第一帧。
一、 Android 9.0(API 级别 28)及以上版本
在 Android 9.0(API 级别 28)及以上版本中使用 ImageView 实现播放 GIF 动画。
private lateinit var animateDrawable: AnimatedImageDrawable
@SuppressLint("UseCompatLoadingForDrawables")
@RequiresApi(Build.VERSION_CODES.P)
fun startAnimate() {
// 加载动画图片
animateDrawable = resources.getDrawable(R.drawable.animate_icon, null) as AnimatedImageDrawable
_binding.imageAnimate.setImageDrawable(animateDrawable)
// 开启动画
animateDrawable.start()
}
@RequiresApi(Build.VERSION_CODES.P)
fun stopAnimate() {
animateDrawable.stop()
}
在布局文件中,只需使用普通的 ImageView 并设置 src 属性即可。
<ImageView
android:id="@+id/image_animate"
android:layout_width="100dp"
android:layout_height="100dp"
android:src="@drawable/animate_icon"/>
二、在 Android 9.0 之前的版本中播放 GIF 动画
在 Android 9.0 之前的版本中,可以使用第三方库(如 Glide 或 Picasso)实现 GIF 图片动画。
1、第三方 Glide 库(推荐)
通过使用 Glide 第三方库,你可以轻松地实现复杂的 GIF 动画效果,无需额外编写代码。
(1)添加依赖库
implementation("com.github.bumptech.glide:glide:4.16.0")
annotationProcessor("com.github.bumptech.glide:compiler:4.16.0")
(2) 代码中调用
fun startAnimateByGlide() {
Glide.with(context)
.asGif()
.load(R.drawable.animate_icon)
.into(_binding.imageAnimate)
}
2、第三方 Picasso 库 (不支持)
Picasso 本身并不支持 GIF 动画的自动播放,只能加载 GIF 文件并显示其第一帧。这是因为 Picasso 主要专注于静态图片的加载和缓存,对于 GIF 动画的支持较为有限。如果你需要自动播放 GIF 动画,建议使用 Glide。
fun startAnimateByPicasso() {
Picasso.get()
.load(R.drawable.animate_icon)
.into(_binding.imageAnimate)
}