Thursday, February 21, 2019

Rotate an image in Canvas

We have an Bitmap icon in Canvas.
Bitmap icon = BitmapFactory.decodeResource(getResources(), R.drawable.abc);
We want to rotate it around it’s centre, use this code.
Matrix ma = new Matrix();
    float angle = (float) (System.currentTimeMillis() % 1000) / 1000 * 360;
ma.reset();
ma.postTranslate(-icon.getWidth() / 2, -icon.getHeight() / 2);
ma.postRotate(angle);
ma.postTranslate(200, 200);                       
canvas.drawBitmap(icon, ma, null);
Note the invalidate() must be call.
The line postTranslate(200, 200); show the position of icon.
If we want it rotate around a radius, use this.
ma.postTranslate(-icon.getWidth()/2, 100);

The radius is 100dp.

No comments:

Post a Comment