Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - paint rotated bitmap into a specific location on canvas

Ok maybe I am missing something here, but I am stuck for hours. I make an app where the user paints a dimension line over a picture. Now I want to paint also some selection points that show that the line is selected. These points are a specific bitmap that must be on the end of the line (after the arrowhead) and be rotated according to the arrow. I have created a class DrawSelectionPoint that extends View and I can rotate the bitmap with something like this:

selectionPoint = BitmapFactory.decodeResource(context.getResources(),
                    R.drawable.selectionpoint);
Matrix matrix = new Matrix();
        matrix.postRotate((float)Math.toDegrees(angle));        
canvas.drawBitmap(selectionPoint, matrix, null);

(where angle is the angle of the line) this way my bitmap is rotated the way I want it but it is painted on point 0,0 (top left of the screen).

If I use something like

canvas.save();

canvas.rotate();

canvas.drawBitmap(selectionPoint, x, y, null);

canvas.restore(); 

then I find it too hard to draw the bitmap at the exact location I want (since I draw on a rotated canvas, which I rotate back afterwards). I tried some Euclidean rotation transformations but I had no luck.

Is there some way to apply the matrix rotation and also give the points where I need the bitmap to be drawn? Thank you in advance!

like image 684
george Avatar asked May 26 '12 10:05

george


1 Answers

assume you want to draw the bitmap where the center of the bitmap will be at (px,py) canvas coordinates. Have a member variable

Matrix matrix = new Matrix();

and in your onDraw:

matrix.reset();
matrix.postTranslate(-bitmap.getWidth() / 2, -bitmap.getHeight() / 2); // Centers image
matrix.postRotate(angle);
matrix.postTranslate(px, py);
canvas.drawBitmap(bitmap, matrix, null);
like image 90
yoah Avatar answered Oct 21 '22 03:10

yoah