播放动态gif作为电影只显示画布背景。

3

我希望在我的Android应用程序中播放一个动态gif图像。

我注意到使用以下代码的WebView可以正常工作:

webview.loadUrl("file:///android_asset/gif.gif");

很遗憾,webView占用的内存太大了,导致我的应用经常崩溃。我看过很多使用Movie的教程,比如这个:
public class GIFView extends View {
    private Movie movie;
    private long moviestart;

    public GIFView(Context context) throws IOException {
        super(context);
        movie = Movie.decodeStream(getResources().getAssets().open("gif.gif"));
    }

    public GIFView(Context context, AttributeSet attrs) throws IOException {
        super(context, attrs);
        movie = Movie.decodeStream(getResources().getAssets().open("gif.gif"));
    }

    public GIFView(Context context, AttributeSet attrs, int defStyle)
            throws IOException {
        super(context, attrs, defStyle);
        movie = Movie.decodeStream(getResources().getAssets().open("gif.gif"));
    }

    private long _start_time;

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

        long _current_time = android.os.SystemClock.uptimeMillis();
        if (0 == _start_time) {
            _start_time = _current_time;
        }
        if (null != movie) {
            final int _relatif_time = (int) ((_current_time - _start_time) % movie
                    .duration());
            movie.setTime(_relatif_time);
            Log.i("",""+_relatif_time);
            double scalex = (double) this.getWidth() / (double) movie.width();
            double scaley = (double) this.getHeight() / (double) movie.height();
            canvas.scale((float) scalex, (float) scaley);
             movie.draw(canvas, (float) scalex, (float) scaley)
        }

        this.invalidate();
    }
}

当我看到一个大的红色窗口时,我可以看到Canvas被绘制了,并且通过我添加的日志,我可以看到我的电影不是空的,而且有一个长度!

不幸的是,除了大的红色矩形,canvas上没有任何东西显示出来,我已经尝试使用不同的gif文件进行测试。

你有什么想法为什么这不起作用吗?

1个回答

7

我尝试了你的代码,确实可以工作。问题在于动画没有考虑GIF帧时间。正如你所知,每一帧都有一个时间(以毫秒为单位),动画制作者必须注意并等待。你的类实现简单地按照恒定速度逐帧播放。 - Colateral

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接