You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android中如何通过AnimatedImageDrawable获取GIF的毫秒级时长?

如何用AnimatedImageDrawable获取GIF总时长

两种可行实现方案

AnimatedImageDrawable确实没有直接暴露时长接口,但可以通过以下两种方式解决:


方案1:通过ImageDecoder手动解析帧延迟

利用ImageDecoder的帧信息API,遍历所有帧累加延迟时间得到总时长:

fun calculateGifDuration(context: Context, gifResId: Int): Long {
    var totalMs = 0L
    val source = ImageDecoder.createSource(context.resources, gifResId)
    // 解码时只获取帧信息,不加载完整Drawable
    ImageDecoder.decodeDrawable(source) { decoder, _, _ ->
        val frameCount = decoder.frameCount
        for (index in 0 until frameCount) {
            totalMs += decoder.getFrameDelay(index)
        }
        decoder.cancel() // 终止解码,节省资源
    }
    return totalMs
}

getFrameDelay()返回的是单帧的延迟毫秒数,累加后就是GIF的总播放时长。


方案2:借助第三方库简化操作

如果不想自己写解析逻辑,用Glide这类图片加载库可以快速拿到时长:

Glide.with(context)
    .asGif()
    .load(gifResId)
    .addListener(object : RequestListener<GifDrawable> {
        override fun onLoadFailed(e: GlideException?, model: Any?, target: Target<GifDrawable>?, isFirstResource: Boolean): Boolean {
            return false
        }

        override fun onResourceReady(resource: GifDrawable?, model: Any?, target: Target<GifDrawable>?, dataSource: DataSource?, isFirstResource: Boolean): Boolean {
            val totalDuration = resource?.totalDuration ?: 0L
            // 在这里处理拿到的时长
            return false
        }
    })

小提示

  • 手动解析时一定要调用decoder.cancel(),避免加载整个GIF到内存,提升性能;
  • 第三方库会增加包体积,按需选择即可。

内容的提问来源于stack exchange,提问作者Bhavin Vala

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 12:18:26