Java 围绕不以位图为中心的点旋转位图
我有一个位图,我想围绕画布上的一个点旋转。我要旋转它的点不是位图的中心。我使用的是矩阵。这是我的一个例子Java 围绕不以位图为中心的点旋转位图,java,android,bitmap,rotation,Java,Android,Bitmap,Rotation,我有一个位图,我想围绕画布上的一个点旋转。我要旋转它的点不是位图的中心。我使用的是矩阵。这是我的一个例子 Bitmap image = ContentManager.getInstance().getImage(imageId); Matrix matrix = new Matrix(); matrix.setTranslate(-image.getWidth()/2f, -image.getHeight()/2f); matrix.postRotate(rota
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);
到
还有很多其他的东西。结果是位图总是远离我预期的位置。将位图围绕屏幕中心旋转90度会使位图与原来的位置成90度角,因此会旋转。位图似乎总是围绕其中心点旋转,然后在屏幕上的随机点结束。旋转对象时,它将围绕原点左上角旋转。首先要平移位图,使轴点变为0,0,旋转位图,然后将其平移回原始位置 您可以尝试以下方法:
matrix.setTranslate(-px, -py);
matrix.postRotate(rotationDegrees);
matrix.setTranslate(px, py);
// Then do other things.
在经历了很多混乱之后,发现这非常困难或有问题,不确定是哪一个,找到了最简单的解决方法是找到位图的新中心,然后将图像放在那里,看起来更复杂,但它在普通旋转/平移不起作用的地方工作
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);
看不出这里的逻辑有什么问题吗?但在我的例子中,位图在这里的视图中不可见
matrix.postTranslate(pivotPoint.x, pivotPoint.y);
matrix.postRotate(angle);
matrix.postTranslate(radius - (bitmap.getWidth()/2f), -bitmap.getHeight()/2f);