【问题标题】:Why is my gif image not animating?为什么我的 gif 图像没有动画?
【发布时间】:2013-11-04 20:34:37
【问题描述】:

我目前正在尝试使用电影在自定义视图中显示 gif 图像。我确实使用了最常见的方法来做到这一点:

public class GifView extends View {

    private Movie movie;
    private long timeElapsed;

    public GifView(Context context) {
        super(context);
        init();
    }

    public GifView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public GifView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        timeElapsed = 0;
        setImage(getResources().openRawResource(R.drawable.sample));
    }

    public void setImage(byte[] bytes) {
        movie = Movie.decodeByteArray(bytes, 0, bytes.length);
        invalidate();
    }

    public void setImage(InputStream is) {
        movie = Movie.decodeStream(is);
        invalidate();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        canvas.drawColor(Color.TRANSPARENT);
        super.onDraw(canvas);

        long now = android.os.SystemClock.uptimeMillis();
        if (timeElapsed == 0) {   // first time
            timeElapsed = now;
        }
        if (movie != null) {
            int dur = movie.duration();
            if (dur == 0) {
                dur = 1000;
            }
            int relTime = (int)((now - timeElapsed) % dur);
            movie.setTime(relTime);
            movie.draw(canvas, getWidth() - movie.width(), getHeight() - movie.height());
            invalidate();
        }
    }
}

这仅在我的手机上显示 GIF 的第一帧(Nexus 4 运行 API 18)。 我已经读过,需要为此视图禁用 hardwareAcceleration 才能使其显示(如果删除相关行,则不显示)。 我已经尝试过使用其他 gif 图像并得到相同的结果。 我注意到的一件事是movie.getDuration() 总是返回 0,这很奇怪吧? 有什么想法吗?

【问题讨论】:

  • 由于您的 GIF 是一种资源,您可以考虑使用我的 gif2animdraw 脚本将 GIF 转换为 AnimationDrawable 和一系列帧:gist.github.com/commonsguy/6757059
  • 很有趣,但我使用这个drawable只是为了测试。最后,我希望能够显示从网络请求中检索到的 GIF
  • 哦,是的,我的脚本无法解决这种情况,抱歉。
  • 不用担心,感谢您的脚本!

标签: android animated-gif


【解决方案1】:

如果您需要在 Android 中正确播放 GIF,我想您应该使用第三个库,因为框架本身不支持该格式。您可能感兴趣的几个项目是

  • ImageViewEx:Android 的 ImageView 扩展,支持动画 GIF 并包含更好的密度管理

  • ION:轻松实现 Android 异步网络。获得了 GIF 支持 few days ago,并且非常适合下载和显示远程 GIF。

【讨论】:

  • 感谢您的回答。上面的代码使用与第一个库相同的方法。第二个库使用 Java gif 解码器。我昨天试过了,不知何故,第二种方法奏效了。我将实现我自己的方式,因为这两个库对于我的需求来说太过分了。无论如何感谢您的评论。
猜你喜欢
  • 2015-05-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-27
  • 2015-07-03
  • 1970-01-01
相关资源
最近更新 更多