Thursday, February 25, 2010

Animation through Bitmap In Android

In Android, we can do frame by frame animation on Bitmaps. For this, first convert the bitmap into drawable objects.

Create a class called "BitmapDrawable" which extends Drawable and pass the bitmap to its constructor. In the draw(), draw the bitmap.


class BitmapDrawable extends Drawable {
private Bitmap mBitmap;

BitmapDrawable(Bitmap b) {
mBitmap = b;
}

@Override
public void draw(Canvas canvas) {
canvas.drawBitmap(mBitmap, 0.0f, 0.0f, null);
}

@Override
public int getOpacity() {
return PixelFormat.TRANSLUCENT;
}

@Override
public void setAlpha(int alpha) {
}

@Override
public void setColorFilter(ColorFilter cf) {
}

@Override
public int getIntrinsicWidth() {
return mBitmap.getWidth();
}

@Override
public int getIntrinsicHeight() {
return mBitmap.getHeight();
}

@Override
public int getMinimumWidth() {
return mBitmap.getWidth();
}

@Override
public int getMinimumHeight() {
return mBitmap.getHeight();
}

public Bitmap getBitmap() {
return mBitmap;
}
}


Create the objects of the "BitmapDrawable" and add the "BitmapDrawable" to the AnimationDrawable using addFrame().


AnimationDrawable animDrawable = new AnimationDrawable();
Drawable frame1 = new BitmapDrawable(bmp);
animDrawable.addFrame(frame1, 250);


Create as many drawable as needed and add it to the AnimationDrawable.


Drawable frame1 = new BitmapDrawable(b1);
animDrawable.addFrame(frame1, 250);
Drawable frame2 = new BitmapDrawable(b2);
animDrawable.addFrame(frame2, 250);
Drawable frame3 = new BitmapDrawable(b3);
animDrawable.addFrame(frame3, 250);
Drawable frame4 = new BitmapDrawable(b4);
animDrawable.addFrame(frame4, 250);
Drawable frame5 = new BitmapDrawable(b5);
animDrawable.addFrame(frame5, 250);
Drawable frame6 = new BitmapDrawable(b6);
animDrawable.addFrame(frame6, 250);

Then create an ImageView and set the background as the animationDrawable.


ImageView img = new ImageView(this);
img.setBackgroundDrawable(animDrawable);


Lastly, create a Handler and call animDrawable.start();


Handler startAnimation = new Handler() {
public void handleMessage(Message msg) {
super.handleMessage(msg);
animDrawable.start();
}
};


and call the handler as


Message msg = new Message();
startAnimation.sendMessage(msg);

No comments:

Post a Comment

Androidians