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)
    }
相关推荐
肯多洛夫斯基1 小时前
安卓工控屏静默连WiFi全攻略
android
极梦网络无忧1 小时前
Android无障碍服务实现抖音直播间界面监控(场控助手核心原理)
android
call me by ur name2 小时前
ERNIE 5.0 Technical Report论文解读
android·开发语言·人工智能·机器学习·ai·kotlin
kerli2 小时前
Compose 组件:Box 核心参数及其 Bias 算法
android·前端
BLUcoding3 小时前
Android 常用控件及核心属性
android
遥不可及zzz3 小时前
[特殊字符] Android AAB 一键安装工具配置指南
android·macos
私人珍藏库3 小时前
【Android】一键硬核锁手机
android·智能手机·app·工具·软件
TTTao23334 小时前
自用Android项目框架备份
android
沃尔威武4 小时前
性能调优实战:从火焰图定位到SQL优化的全流程
android·数据库·sql
Fᴏʀ ʏ꯭ᴏ꯭ᴜ꯭.4 小时前
基于MySQL一主一从环境添加多个新从库
android·mysql·adb