0

I am drawing a number of shapes on a canvas. One such shape is a bitmap. Say the center of the bitmap on the canvas is at center xCenter, yCenter such that to draw I call

xLeft = xCenter+mBitmap.getWidth()/2;
yTop = yCenter+mBitmap.getHeight()/2;
canvas.drawBitmap(mBitmap, x,y, mFilledPaint);

So far everything works fine. The next step is to rotate the bitmap around the center xCenter, yCenter. My code below is not doing it. It moves the bitmap all over the place, whereas all I want is for the image to rotate in place around its own center. How can I fix the code below? I already looked at Android: How to rotate a bitmap on a center point and at best I don't understand the responses there.

My code

xLeft = xCenter+mBitmap.getWidth()/2;
yTop = yCenter+mBitmap.getHeight()/2;
matrix.postRotate(30f, xLeft, yTop);
canvas.drawBitmap(mBitmap, matrix, mFilledPaint);

also replacing xLeft and yTop with 0 does not seem to work.. any idea ??

Edit:

xCenter, yCenter is not the center of the canvas. It's just the point where the center of the bitmap lands.

Community
  • 1
  • 1
learner
  • 11,490
  • 26
  • 97
  • 169

1 Answers1

1

i guess you mean, you can not understand following code:

this.matrix.reset();
this.matrix.setTranslate(this.floatXpos, this.floatYpos);
this.matrix.postRotate((float)this.direction, this.getCenterX(), this.getCenterY()); 

I think i could give some explanation about this, since i done this task in my project before:

  1. the first line to rest it to identity, which means do thing, because any thing times identity matrix get itself.
  2. the second line, move the original point to the target position,this is actually specify xLeft and yTop to which the bitmap will draw in canvas.
  3. the thrid line, rotate around center point (xLeft+bitmapWidth/2,yTop+Height/2)

To understand this, you need to know how the matrix is used.basically, you bitmap (the points in bitmap is a matrix actually) times the matrix you created here, then it get a new matrix, canvas just draw that new matrix.

Liangxiong.ZHU
  • 335
  • 1
  • 3
  • 7
  • thanks for the details. As a final step I do `canvas.drawBitmap(mBitmap, matrix, mFilledPaint);`. But the problem is that the bitmap is drawn about some external center as opposed to its center, not by very much but by enough to be very noticeable. If fact it's by about half the length of the bitmap or so. I am playing around with that but not much luck yet. – learner Jan 19 '14 at 05:55