如何在Android中旋转位图,使图像中心平滑,无振荡运动

问题描述 投票:7回答:3

我想基于用户点击10度旋转位图图像。在众多stackoverflow和谷歌答案之后,我尝试了Matrix旋转的各种组合。

然而,图像并没有像预期的那样真正旋转,并且给出了关于画布中心的旋转+振荡的抖动视图。为了测试,每次调用对象的绘制方法时,我都会将旋转角度增加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);

 }
android image rotation smooth
3个回答
18
投票

这是一个例子。我打破了它的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,并通过调用matrix.reset()替换创建


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处绘制位图中心,那么您可以更改我的代码以在中心绘制它,它将按您的意愿工作。

希望这可以帮助!


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. 恢复图像
© www.soinside.com 2019 - 2024. All rights reserved.