我想在我的应用程序中显示动画GIF图像。 我发现Android本身并不支持GIF动画。

但是它可以使用AnimationDrawable显示动画:

开发>指南>图像和图形>绘图概述

这个例子使用动画保存为框架的应用程序资源,但我需要的是直接显示动画gif。

我的计划是将动画GIF分解为帧,并将每帧添加为可绘制的AnimationDrawable。

有人知道如何从动画GIF中提取帧并将它们转换为可绘制的吗?


当前回答

如果你想使用Glide加载gif:

Glide.with(this)
        .asGif()
        .load(R.raw.onboarding_layers) //Your gif resource
        .apply(RequestOptions.diskCacheStrategyOf(DiskCacheStrategy.NONE))
        .listener(new RequestListener<GifDrawable>() {
            @Override
            public boolean onLoadFailed(@Nullable @org.jetbrains.annotations.Nullable GlideException e, Object model, Target<GifDrawable> target, boolean isFirstResource) {
                return false;
            }

            @Override
            public boolean onResourceReady(GifDrawable resource, Object model, Target<GifDrawable> target, DataSource dataSource, boolean isFirstResource) {
                resource.setLoopCount(1);
                return false;
            }
        })
        .into((ImageView) view.findViewById(R.id.layer_icons));

其他回答

没有人提到Ion或Glide库。它们工作得很好。

与WebView相比,它更容易处理。

首先,Android浏览器应该支持动画gif。如果没有,那就是bug!看一下问题跟踪器。

如果你在浏览器外显示这些动画gif,情况可能就不一样了。要做到你所要求的,将需要外部库,支持动画gif解码。

第一个接口是Java2D或JAI (Java Advanced Imaging) API,如果Android Dalvik在你的应用程序中支持这些库,我会感到非常惊讶。

使用ImageViewEx,一个库,使使用gif像使用ImageView一样简单。

最简单的方法-可以考虑下面的代码

我们可以利用Imageview的setImageResource,参考下面的代码相同。

下面的代码可以用来显示像gif一样的图像,如果你有gif的多次分割图像。只需从在线工具中将gif分割成单独的png,并按照以下顺序将图像放入可绘制图中

Image_1.png, image_2.png等等。

让处理程序动态地更改图像。

int imagePosition = 1;
    Handler handler = new Handler();
        Runnable runnable = new Runnable() {
            public void run() {
                updateImage();
            }
        };




    public void updateImage() {

                appInstance.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        int resId = getResources().getIdentifier("image_" + imagePosition, "drawable", appInstance.getPackageName());
                        gifImageViewDummy.setImageResource(resId);
                        imagePosition++;
    //Consider you have 30 image for the anim
                        if (imagePosition == 30) {
//this make animation play only once
                            handler.removeCallbacks(runnable);

                        } else {
    //You can define your own time based on the animation
                            handler.postDelayed(runnable, 50);
                        }

//to make animation to continue use below code and remove above if else
// if (imagePosition == 30)
//imagePosition = 1;
// handler.postDelayed(runnable, 50);
// 
                    }
                });
              }

Android实际上可以解码和显示动画gif,使用Android。graphics。movie类。

这没有太多的文档,但是在SDK Reference中有。此外,它被用于ApiDemos在BitmapDecode的例子中的样本与一些动画标志。