Pregunta

I'm currently trying to show a gif image in a custom view using a movie. I've literally used the most common way to do this:

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();
        }
    }
}

This displays only the first frame of the GIF on my phone (Nexus 4 running API 18). I've read that disabling the hardwareAcceleration for this view is required in order to make it show (nothing show if I remove the related line). I've tried that with other gif images and got the same result. One thing I've noticed is that movie.getDuration() is always returning 0, which is weird right? Any idea?

¿Fue útil?

Solución

If you need to correctly play GIFs in Android I suppose you should use a third library, because the framework doesn't support the format natively. A couple of projects you could be interested in are

  • ImageViewEx: Extension of Android's ImageView that supports animated GIFs and includes a better density management

  • ION: Android Asynchronous Networking Made Easy. Got the GIF support few days ago and is explicitly suited for downloading and showing remote GIFs.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top