【问题标题】:Rotating a Bitmap around a point NOT center to bitmap围绕一个点而不是中心旋转位图到位图
【发布时间】:2015-05-05 01:19:04
【问题描述】:

我有一个位图,我想围绕画布上的一个点进行旋转。我要旋转它的点不是位图的中心。我正在使用矩阵。这是我所拥有的一个示例。

    Bitmap image = ContentManager.getInstance().getImage(imageId);
    Matrix matrix = new Matrix();
    matrix.setTranslate(-image.getWidth()/2f, -image.getHeight()/2f);
    matrix.postRotate(rotationDegrees);
    matrix.postTranslate(x / scaleX, y / scaleY);
    matrix.postScale(scaleX, scaleY);
    paint.setAlpha(alpha);
    canvas.drawBitmap(image, matrix, paint);

我想稍微操纵这段代码,使其不围绕位图的中心点旋转,而是围绕不同的点旋转。为了更清楚地说明,我创建了这张图片:

.

我已经尝试了所有我能想到的设置

    matrix.setTranslate(-image.getWidth()/2f, -image.getHeight()/2f);

到

    matrix.setTranslate(pivotPoint.x, pivotPoint.y);

还有很多其他的东西。结果是位图总是偏离我预期的位置。 (例如,将其围绕屏幕中心旋转 90 度会使位图与原来的位置成 90 度,因此会被旋转。)位图似乎总是围绕其中心点旋转,然后最终出现在屏幕上的一个随机点屏幕。

【问题讨论】:

    标签: java android bitmap rotation


    【解决方案1】:

    经过一番折腾,发现这个非常困难或错误,不确定是哪个,找到最简单的解决方案是找到位图的新中心并将图像放在那里,看起来更复杂,但它适用于普通旋转/translation 不是。

      float angle;
      float radius;
    
      Bitmap wheelSelectBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.image);
      Matrix matrix = new Matrix();
    
      Point pivotPoint = new Point();
      pivotPoint.set(pivotPoint.x, pivotPoint.y)
      Point newCenter = new Point();
      newCenter.set((int)(pivotPoint.x + (radius * Math.cos(angle)), (int)(pivotPoint.y - (radius * Math.sin(angle)));
    
      matrix.postTranslate(newCenter.x - (bitmap.getWidth()/2f), newCenter.y - (bitmap.getHeight()/2f));
      matrix.postRotate(angle, newCenter.x, newCenter.y);
    
      Bitmap rotatedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), null, true);
      canvas.drawBitmap(bitmap, matrix, null);
    

    这可能并不完美,但这种方式解决了我的问题,并阻止了位图在商店各处飞来飞去。与您的图表不同,默认情况下它也会顺时针旋转,因此只需使用 -angle 逆顺时针。不知道这里发生了什么,因为这段代码肯定没有达到我想要的效果:

     matrix.postTranslate(pivotPoint.x, pivotPoint.y);
     matrix.postRotate(angle);
     matrix.postTranslate(radius - (bitmap.getWidth()/2f), -bitmap.getHeight()/2f);
    

    看不出这里的逻辑有什么问题?但在我的情况下,位图在此处的视图中不可见。

    【讨论】:

      【解决方案2】:

      旋转物体时,它会绕原点(左上角)旋转。您需要先平移位图,使轴心点变为 (0, 0),然后旋转位图,然后再平移回原来的位置。

      你可以试试这样的:

      matrix.setTranslate(-px, -py);
      matrix.postRotate(rotationDegrees);
      matrix.setTranslate(px, py);
      // Then do other things.
      

      【讨论】:

        猜你喜欢
        • 2015-05-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-01-24
        相关资源
        最近更新 更多