Monday, June 22, 2015

// //

GIF animation on android

Today i'm going to show you how to implement gif very easy and effective. this time we will not used any xml. MainActivity.java

import android.support.v7.app.ActionBarActivity;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends Activity {

@Override
public void onCreate(Bundle savedInstanceState){

super.onCreate(savedInstanceState);

//we have set the contentview in MYGIFView activity it means 
//we will not use any xml..
setContentView(new MYGIFView(this));

}
}

MYGIFView.java

import java.io.InputStream;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Movie;
import android.graphics.Paint;
import android.view.View;

public class MYGIFView extends View{

 
Movie movie,movie1;
InputStream is=null,is1=null;
long moviestart;

public MYGIFView(Context context) {
super(context);

//please provide your own giffile

is=context.getResources().openRawResource(R.drawable.anim2);
movie=Movie.decodeStream(is);

}

@Override
protected void onDraw(Canvas canvas) {

canvas.drawColor(Color.WHITE);
super.onDraw(canvas);

//double the view
//movie.draw(canvas, ((float) this.getWidth() / (float) movie.width()),
//(float) this.getHeight() / (float) movie.height());


long now=android.os.SystemClock.uptimeMillis();
System.out.println("now="+now);
if (moviestart == 0) { // first time
moviestart = now;

}

System.out.println("\tmoviestart="+moviestart);
int relTime = (int)((now - moviestart) % movie.duration()) ;
System.out.println("time="+relTime+"\treltime="+movie.duration());
movie.setTime(relTime);
movie.draw(canvas,this.getWidth()/2-20,this.getHeight()/2-40);
this.invalidate();
}


}

You have to provide your own gif image file! Thats all! Just test it and run it not on the emulator because it maybe distorted, just run on the real device instead.