Rotate a Bitmap using matrix

If you are an Android app developer and is working on a game or some other animation project, chances are you might find giving animation to the bitmaps. And when the animation is to rotate the bitmap, the problem increases manifolds. There’re several ways in which you can achieve this objective, such as using RotateAnimation class, but they sometime confuses me, so I use matrix (Mr. Anderson??)  argument of Bitmap constructor. This makes it easier to do. let me show it to you with an example:

Note: I am using this code in the custom View, and using separate method for returning the Matrix. You can have separate class for Bitmap and can call it from there.

public void onDraw(Canvas c){
    Paint p=new Paint();
    Bitmap bm=BitmapFactory.decodeResource(getResources(), R.drawable.bitmap);
    c.drawBitmap(bm, rotateMe(), p);
    invalidate();
}

public Matrix rotateMe(){
    Matrix mtx=new Matrix();
    mtx.postRotate(deg,bm.getWidth()/2,bm.getHeight()/2);
    mtx.postTranslate(x, y);  //The coordinates where we want to put our bitmap
    deg=deg-10; //degree of rotation
    return mtx;
}

Kindly comment your suggestions and questions about this.

Thanks

Advertisements

10 comments on “Rotate a Bitmap using matrix

  1. Pingback: Electronics For Everyone - On Fire Matrix Internet Home Business Opportunity {2×2 Matrix Program}

  2. Its working fine, but the image is getting slightly blur when i rotate it by (60,120,210,240,300) degree but work fine for (0,180,360) degree

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s