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)
    }
相关推荐
平头哥AI11 小时前
Day 22 _ 包装错误别丢链_%w、errors.Is 与 errors.As
android·服务器·学习·golang·go
聚美智数11 小时前
图片广告检测-图片审核-图片广告识别-图像广告检测
android
早睡早起身体好12314 小时前
用 XGrammar 约束大模型工具调用:解决参数为空的问题
android·人工智能·神经网络·机器学习·自然语言处理·vllm
大佐不会说日语~16 小时前
Android 16 下 uni-app APP 提示“网络连接失败”的排障与修复
android·uni-app
2501_9151063217 小时前
苹果App Store上架费用及流程全面解析
android·ios·小程序·https·uni-app·iphone·webview
YF021118 小时前
Android 16系统App开机自启动方案
android
hm宋19 小时前
安卓手机卡顿优化 —— 背景与使用指南
android
OxYGC20 小时前
[Android] [WatchOS]智能手表第一篇: 实用工具与应用推荐
android·智能手表
嘟哩DuliDuli21 小时前
创作 Agent 的任务状态该如何保存
android·java·javascript