如何在Android中平滑地围绕图像中心旋转位图,而不会产生振荡运动

7
我想根据用户点击将位图图像旋转10度。在查看了许多stackoverflow和Google答案后,我尝试了各种矩阵旋转组合。
然而,图像并没有按预期旋转,并且在画布中心周围产生了抖动的旋转视图+振荡。为了测试,每次调用对象的绘制方法时,我增加10度的旋转角度(而不是点击)。图像是一个对称的圆形[64x64包围矩形],我希望它像车轮一样围绕自己的中心在屏幕中心旋转,但它会对角线向右下方旋转并以振荡方式向屏幕中心移动。
 public void draw(Canvas canvas) {
    Matrix matrix = new Matrix();

    rotation += 10;
    float px = this.viewWidth/2;
    float py = this.viewHeight/2;
    matrix.setRotate(rotation, bitmap.getWidth()/2, bitmap.getHeight()/2);
    Bitmap newbmp = Bitmap.createBitmap(bitmap, 0, 0, getImgWidth(), getImgHeight(), matrix, true);
    canvas.drawBitmap(newbmp, px - (getImgWidth()/2), py - (getImgHeight()/2), null);

 }
3个回答

19

这是一个例子。 我将它分为3个步骤。 第一步是移动位图,使其中心位于0,0处。 然后进行旋转, 最后将位图中心移动到画布上所需位置。 您不需要第二个位图。

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);

为优化起见,可以在此方法外部创建矩阵,并将其创建替换为调用 matrix.reset()


2
非常感谢!通过将矩阵移出“绘制”方法并确保矩阵没有被重置(可获得平滑旋转效果),我成功解决了问题。还使用了 matrix.setRotate(rotation, bitmap.getWidth()/2, bitmap.getHeight()/2); 替换了前两个 post* 方法。 - Anshul
谢谢你的回答。它救了我的一天。 - Siddharth
这是哪个视图? - Akshatha S R
如何获取位图(缩放位图)? - Hiren Dabhi
不必先将其平移至中心点再进行翻译,您可以使用 matrix.postTranslate(px, py, centerx, centery) - Ionoclast Brigham

0

你需要将位图转换到0,0点(或在0,0处绘制它),然后在那里旋转它,最后再将其转回来,如下所示:

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

我在这里以0,0为中心绘制它(我认为),因为旋转时是围绕0,0而不是屏幕中心进行的。如果你将中心点绘制在0,0处,那么它将围绕位图的中心旋转。

如果我的代码没有实现以0,0为中心绘制位图,那么你可以更改我的代码以在中心绘制它,这样它就能按照你想要的方式工作。

希望这有所帮助!


以上的方法让情况变得更糟。现在我的轮子向右下角移动并围绕右下角振荡,而背景和其他物体“看起来”仍然是原样。canvas.translate 只是简单地移动了轮子中心。 - Anshul
如果你使用 getImgWidth()/2getImgHeight()/2 而不是视图尺寸来进行翻译,那么这实际上是有效的。 - Ja͢ck

0
// 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();

步骤如下:

  1. 保存现有画布
  2. 围绕位于画布中心的位图旋转画布,使其产生旋转角度
  3. 绘制图片
  4. 恢复画布

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接