用Glide控制GIF动画

Controlling GIF animation with Glide

我正在使用 Glide 将动画 GIF 动画加载到 ImageView。它按预期工作,无限循环:

GlideApp.with(getContext())
            .load(R.raw.my_gif_animation)
            .into(this)

我想在每次 GIF 动画循环开始(或结束)时添加振动,但我找不到任何回调、侦听器或帧计数器,我可以用它来了解动画循环何时开始(或结束)。欢迎在 JavaKotlin 中回答。

我找到了解决问题的方法,原来我们可以在资源加载后访问GIF动画的帧。在 运行 Thread 中使用此信息,我不仅能够听到动画的 end/start,而且还能根据动画帧非常精确地调整时间。

这是我在 Kotlin 中的工作代码(在 Java 中会非常相似):

GlideApp.with(getContext())
            .asGif()
            .load(R.raw. my_gif_animation)
            .apply(RequestOptions.diskCacheStrategyOf(DiskCacheStrategy.NONE))
            .listener(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 {
                    myThread = Thread(Runnable {
                        while (true) {
                            if (resource?.isRunning == true) {
                                if (resource.frameIndex == 10).toInt()) {
                                    // This code will be executed every time the 10th frame of the GIF animation is played.. 
                                }
                                if (Thread.interrupted()) break
                            }
                        }
                    })
                    myThread?.start()
                    return false
                }
            })
            .into(this)