首先我得抱怨一句,不记得看了谁写的一句关于android 不能够实现gif图片的话,一直深深的误导了我整整3个月,今天我在这向大家提供一种实现gif的方法,废话到此结束,下面是代码:
转载请申明地址:http://blog.csdn.net/yan_daoqiu
public class SampleView extends View {
private Movie mMovie;
private Bitmap mBitmap;
private Canvas mCanvas;
private long mMovieStart;
private byte[] streamToBytes(InputStream is) {
ByteArrayOutputStream os = new ByteArrayOutputStream(1024);
byte[] buffer = new byte[1024];
int len;
try {
while ((len = is.read(buffer)) >= 0) {
os.write(buffer, 0, len);
}
} catch (java.io.IOException e) {
}
return os.toByteArray();
}
public SampleView(Context context) {
super(context);
setFocusable(true);
InputStream is;
is = context.getResources().openRawResource(R.drawable.aa_gif);
if (true) {
mMovie = Movie.decodeStream(is);
} else {
byte[] array = streamToBytes(is);
mMovie = Movie.decodeByteArray(array, 0, array.length);
}
int w = mMovie.width();
int h = mMovie.height();
Log.i("-------width-------", w+"");
Log.i("-------height-------", h+"");
// int[] pixels = new int[w*h];
mBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
mCanvas = new Canvas(mBitmap);
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(0xFFCCCCCC);
Paint p = new Paint();
p.setAntiAlias(true);
// canvas.drawBitmap(mBitmap, 300, 300, null);
long now = android.os.SystemClock.uptimeMillis();
if (mMovieStart == 0) { // first time
mMovieStart = now;
}
if (mMovie != null) {
int dur = mMovie.duration();
if (dur == 0) {
dur = 1000;
}
int relTime = (int)((now - mMovieStart) % dur);
mMovie.setTime(relTime);
//-------------
//mMovie.draw(canvas, 200, 200);
//
//-----------------------
mCanvas.drawColor(0xFFCCCCCC);
mMovie.draw(mCanvas, 0, 0);
Bitmap bitmap = Bitmap.createScaledBitmap(mBitmap, 300, 300, false);
mBitmap.createScaledBitmap(mBitmap, 200, 300, false);
canvas.drawBitmap(bitmap, 100, 200, null);
//--------------------------------
invalidate();
}
}
}