Android 位图-矩阵操作(缩放、旋转和平移)

Android 位图-矩阵操作(缩放、旋转和平移),android,matrix,android-canvas,Android,Matrix,Android Canvas,我需要一些矩阵运算方面的帮助。我想要实现的是: 缩小 移动到特定位置 旋转一定程度(在位图的中心) 我的代码当前如下所示: Matrix matrix = new Matrix(); matrix.preRotate(mShip.getRotation(), mShip.getX() + mShip.getCurrentBitmap().getWidth()/2f, mShip.getY() + mShip.getCurrentBitmap(

我需要一些矩阵运算方面的帮助。我想要实现的是:

  • 缩小
  • 移动到特定位置
  • 旋转一定程度(在位图的中心)
我的代码当前如下所示:

            Matrix matrix = new Matrix();
            matrix.preRotate(mShip.getRotation(), mShip.getX() + mShip.getCurrentBitmap().getWidth()/2f, mShip.getY()  + mShip.getCurrentBitmap().getHeight()/2f);
            matrix.setScale((1.0f * mShip.getWidth() / mShip.getCurrentBitmap().getWidth()), (1.0f * mShip.getHeight() / mShip.getCurrentBitmap().getHeight()));
            matrix.postTranslate(mShip.getX(), mShip.getY());
            mCanvas.drawBitmap(mShip.getCurrentBitmap(), matrix, mBasicPaint);
但是旋转的中心是错误的,我不知道如何解决这个问题——我已经四处查看过了,但只发现了类似的问题,没有解决方法。 我想我可能必须将其中一个操作应用于另一个操作的值,因为它们是按顺序执行的,但我不知道如何执行。

请尝试以下代码:

Matrix matrix = new Matrix();
matrix.setTranslate(-mShip.getCurrentBitmap().getWidth()/2f, -mShip.getCurrentBitmap().getHeight()/2f);
matrix.postRotate(mShip.getRotation());
matrix.postTranslate(mShip.getX(), mShip.getY());
matrix.postScale((1.0f * mShip.getWidth() / mShip.getCurrentBitmap().getWidth()), (1.0f * mShip.getHeight() / mShip.getCurrentBitmap().getHeight()), mShip.getX(), mShip.getY());
请尝试以下代码:

Matrix matrix = new Matrix();
matrix.setTranslate(-mShip.getCurrentBitmap().getWidth()/2f, -mShip.getCurrentBitmap().getHeight()/2f);
matrix.postRotate(mShip.getRotation());
matrix.postTranslate(mShip.getX(), mShip.getY());
matrix.postScale((1.0f * mShip.getWidth() / mShip.getCurrentBitmap().getWidth()), (1.0f * mShip.getHeight() / mShip.getCurrentBitmap().getHeight()), mShip.getX(), mShip.getY());

谢谢,但是现在的译文太离题了。我通过将postTranslate更改为postTranslate(getX()+getWidth()/2f,getY()+getHeight()/2f)修复了它,现在它可以工作了!非常感谢你。你能给我一个提示/解释为什么需要这两种翻译吗?第一种翻译需要将图像中心移动到(0,0),这样它就可以围绕图像中心旋转。完成此操作后,可以将其移动到目标点并进行缩放。谢谢,但现在的平移距离顶部和后部太远了。我通过将postTranslate更改为postTranslate(getX()+getWidth()/2f,getY()+getHeight()/2f)修复了它,现在它可以工作了!非常感谢你。你能给我一个提示/解释为什么需要这两种翻译吗?第一种翻译需要将图像中心移动到(0,0),这样它就可以围绕图像中心旋转。完成此操作后,可以将其移动到目标点并缩放。