How to rotate a bitmap in Android about images center smoothly without oscillatory movement

杀马特。学长 韩版系。学妹 提交于 2019-12-05 05:39:35

Here is an example. I broke it to 3 steps. The first translate moves the bitmap so that it's center is at 0,0 Then a rotation, and finally move the bitmap center to where you want it on the canvas. You don't need the second bitmap.

Matrix matrix = new Matrix();
rotation += 10;
float px = this.viewWidth/2;
float py = this.viewHeight/2;
matrix.postTranslate(-bitmap.getWidth()/2, -bitmap.getHeight()/2);
matrix.postRotate(rotation);
matrix.postTranslate(px, py);
canvas.drawBitmap(bitmap, matrix, null);

As an optimization, create the Matrix once outside this method and replace the creation with a call to matrix.reset()

You need to translate the bitmap to the 0,0 point (or draw it at 0,0) and rotate it there, then translate it back, as such:

canvas.save();
    canvas.translate(this.viewWidth, this.viewHeight);
    canvas.rotate(rotation);
    canvas.drawBitmap(newbmp, -(getImgWidth()/2), -(getImgHeight()/2), null);
canvas.restore();

Here I draw it with the center at 0,0 (I think), because when you rotate, it's about 0,0 and not the center of the screen as one would think. If you draw the center at 0,0 then it will rotate about the center of the bitmap.

If my code does not accomplish drawing the bitmap center at 0,0 then you can change my code to draw it at the center and it will work as you want.

Hope this helps!

// x : x coordinate of image position
// y : y coordinate of image position
// w : width of canvas
// h : height of canvas
canvas.save();
canvas.rotate(angle, x + (w/2), y + (h/2));
canvas.drawBitmap(image, x, y, null);
canvas.restore();

The steps are

  1. Save the existing canvas
  2. Rotate the canvas about the center of the bitmap, that you would draw on canvas with an angle of rotation
  3. Draw the image
  4. Restore the image
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!