Android 中实现 GIF 图片动画

在 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)
    }
相关推荐
2501_915106321 天前
iOS 26 APP 性能测试实战攻略:多工具组合辅助方案
android·macos·ios·小程序·uni-app·cocoa·iphone
怪兽20141 天前
IntentService 的应用场景和使用方式?
android·面试
Jeled1 天前
云信im在Android中的使用2
android
Jerry1 天前
Compose 自定义布局和图形
android
杨筱毅1 天前
【Android】【底层机制】组件生命周期以及背后的状态管理
android·底层机制
Jeled1 天前
Kotlin 实现社交 App 音视频模块:语音录制、播放、暂停与进度控制全流程封装
android·kotlin·android studio·音视频
沐怡旸1 天前
【底层机制】【Android】Binder架构与原理
android·面试
Jeled1 天前
Jetpack —> Media3的分析和使用
android
木易士心1 天前
Android setContentView源码与原理分析
android
00后程序员张1 天前
iOS混淆与IPA文件加固全流程实战 防止苹果应用被反编译的工程级方案
android·ios·小程序·https·uni-app·iphone·webview