masood elsad
masood elsad

Reputation: 438

when rotate using matrix, i lose position of image

I am using canvas to draw multiple images (120X120) when I rotate 60 degrees, the picture stop being centered. The Image can be anywhere on the screen when rotating, i just want to mantain its center. How to do this?

Matrix matrix = new Matrix();
matrix.postRotate(60);
Bitmap map= Bitmap.createBitmap(resizedBitmap, 0, 0,resizedBitmap.getWidth(), resizedBitmap.getHeight(),matrix, true);

Upvotes: 1

Views: 691

Answers (1)

masood elsad
masood elsad

Reputation: 438

I found a solution for my question.

The trick is to use the height and width of the image when drawing them, so when these attributes changes, the position of the rotated image change too

So, as we know, to draw a bitmap, you pass the coordinates of the top left corner. But the correct way of doing it is by passing the coordinates of the center minus the height/width of the image, and when the image height and width change, you maintain the center.

canvas.drawBitmap(map, x  - map.getWidth() / 2,y - map.getHeight() / 2, null);

where x and y are the coordinates of the center of your image

Assume the current situation image size 120X120dp I want to draw my image at 400,300 which means the center of my image will be at 460,360 so, to keep the center of my image always at this cords, I should do this

canvas.drawBitmap(map, 460  - map.getWidth() / 2,360 - map.getHeight() / 2, null);

so, when my image is rotated, its center will stay the same, because the height and width changed, and i am using them to calculate the center.

Just thought of sharing this knowleges, as I found lot of people asking when I was searching for a solution, but no clear good answer was there. Happy programming every one

Upvotes: 1

Related Questions