9

I've been looking at the documentation and the only drawBitmap() that allows a Matrix as parameter doesn't take any kind of screen coordinates by parameter.

I'm using the following code to draw my bitmap with a matrix rotation:

Matrix matrix = new Matrix();
matrix.setRotate(rotation,bitmap.getWidth()/2,bitmap.getHeight()/2);
canvas.drawBitmap(bitmap, matrix, null);

Which of course draws my bitmap at 0,0. How can I set the position and use the matrix?

Ideally I'd like to use the destination Rect:

this.destRect = new Rect(   
                    x - spriteWidth / 2,
                    y - spriteHeight / 2,
                    x + spriteWidth / 2,
                    y + spriteHeight /2
);

Edit:

Following suggestin in comment I tried this:

    Matrix matrix = new Matrix();
    matrix.setTranslate(x, y);
    matrix.setRotate(rotation,bitmap.getWidth()/2,bitmap.getHeight()/2);
    canvas.drawBitmap(bitmap, matrix, null);

but to no avail. Bitmap is still drawn at 0,0

Edit2:

Here's the trick to rotate an image on itself using a matrix and then place it at x,y:

    Matrix matrix = new Matrix();
    matrix.reset();
    matrix.postTranslate(-bitmap.getWidth() / 2, -bitmap.getHeight() / 2); // Centers image
    matrix.postRotate(rotation);
    matrix.postTranslate(x, y);
    canvas.drawBitmap(bitmap, matrix, null);
Juicy
  • 11,840
  • 35
  • 123
  • 212
  • 1
    maybe setTranslate http://developer.android.com/reference/android/graphics/Matrix.html#setTranslate(float, float) – JRowan Nov 18 '14 at 21:47
  • @JRowan Thanks for the answer! I gave it a try but couldn't get it to work (see update). – Juicy Nov 18 '14 at 22:07
  • check this one out, you can translate the canvas then restore it http://stackoverflow.com/questions/18709360/scaling-and-translating-a-bitmap-in-android – JRowan Nov 18 '14 at 22:14
  • @JRowan thanks for the link, the trick is to `postTranslate` and center the image on itself, then `postRotate` then `postTranslate` the image to the desired coords (see update) – Juicy Nov 18 '14 at 23:13

0 Answers0