【问题标题】:How to rotate a bitmap in Android about images center smoothly without oscillatory movement如何在Android中围绕图像中心平滑旋转位图而没有振荡运动
【发布时间】:2012-11-04 03:36:30
【问题描述】:

我想根据用户点击将位图图像旋转 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);

 }

【问题讨论】:

    标签: android image rotation smooth


    【解决方案1】:
    // 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. 恢复图片

    【讨论】:

      【解决方案2】:

      这是一个例子。 我把它分成了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()的调用

      【讨论】:

      • 非常感谢!通过将矩阵移出“绘制”方法并确保矩阵不会重置[提供平滑的旋转效果]来实现这一点。还使用了matrix.setRotate(rotation, bitmap.getWidth()/2, bitmap.getHeight()/2);,而不是前两个 post* 方法。
      • 感谢您的回答。它节省了我的时间。
      • 这里是哪个视图?
      • 我如何获得位图(缩放位图)?
      • 您可以使用matrix.postTranslate(px, py, centerx, centery),而不是先将其翻译一半到中心点。
      【解决方案3】:

      您需要将位图平移到 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只需移动车轮中心
      • 如果你翻译 getImgWidth()/2getImgHeight()/2 而不是视图尺寸,这实际上是有效的。
      猜你喜欢
      • 2011-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-14
      • 1970-01-01
      • 2014-05-19
      • 2020-05-19
      • 1970-01-01
      相关资源
      最近更新 更多