Showing gif in android

Good start.
Gotta make it more useful for loading different gifs after being added to the view and for either assets or resources. Also, for devices with hardware acceleration I was getting blank views, so I turned it off for this GIFView.

Also, be sure to put animated gifs in the res/drawable-xhdpi directory (or assets if using that way)

public class GIFView extends View{

    Movie movie;
    long moviestart;

    public GIFView(Context context) throws IOException { 
        super(context);
    }
    public GIFView(Context context, AttributeSet attrs) throws IOException{
        super(context, attrs);
    }
    public GIFView(Context context, AttributeSet attrs, int defStyle) throws IOException {
        super(context, attrs, defStyle);
    }

    public void loadGIFResource(Context context, int id)
    {
        //turn off hardware acceleration
        this.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        InputStream is=context.getResources().openRawResource(id);
        movie = Movie.decodeStream(is);
    }

    public void loadGIFAsset(Context context, String filename)
    {
        InputStream is;
        try {
            is = context.getResources().getAssets().open(filename);
            movie = Movie.decodeStream(is);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (movie == null) {
            return;
        }

        long now=android.os.SystemClock.uptimeMillis();

        if (moviestart == 0) moviestart = now;

        int relTime;
        relTime = (int)((now - moviestart) % movie.duration());
        movie.setTime(relTime);
        movie.draw(canvas,10,10);
        this.invalidate();
    }
}

Usage:

imageView.loadGIFResource(this, R.drawable.quickguide_1);

and

<com.eyeverify.GIFView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="50dp"
        android:layout_marginTop="110dp"
        android:src="https://stackoverflow.com/questions/7777315/@drawable/quickguide_1"/>

Leave a Comment