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)
    }
相关推荐
summerkissyou198714 小时前
Android - 摄像头 - hal - 开发教程,例子,常见问题,分析方法,解决方案
android
summerkissyou198714 小时前
Android 16 架构图
android
神龙天舞200115 小时前
MySQL 备库为什么会延迟好几个小时
android·数据库·mysql
码农coding18 小时前
android12 systemUI 之锁屏
android
圆山猫18 小时前
[Virtualization](三):RISC-V H-extension 与 Guest 执行模式
android·java·risc-v
爱笑鱼19 小时前
Binder(七):getCallingUid() 读到的是谁?clearCallingIdentity() 又清掉了什么?
android
2501_915909061 天前
iOS 应用反调试技详解术 检测调试器的原理与防护实践
android·ios·小程序·https·uni-app·iphone·webview
Lvan的前端笔记1 天前
AndroidX 完全入门指南
android·androidx
帅次1 天前
Android 应用高级面试:Window 近1年高频追问 18 题
android·面试·职场和发展
总捣什么乱11 天前
MySQL MySQL是怎么保证主备一致的?
android·mysql·adb