[英]Rotating a Bitmap around a point NOT center to bitmap
我有一个要在画布上旋转的点位图。 我要旋转的点不是位图的中心。 我正在使用矩阵。 这是我所拥有的一个例子。
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度,因此将其旋转。)位图似乎总是围绕其中心点旋转,然后最终出现在屏幕上的一个随机点上屏幕。
旋转对象时,它将绕原点旋转(左上角)。 您将需要首先平移位图,以使枢轴点变为(0,0),旋转位图,然后平移回其原始位置。
您可以尝试这样的事情:
matrix.setTranslate(-px, -py);
matrix.postRotate(rotationDegrees);
matrix.setTranslate(px, py);
// Then do other things.
经过一番混乱之后,发现这是非常困难的或越野车,不确定是找到最简单的解决方案是找到位图的新中心,然后将图像放到那里,看起来更复杂,但是在没有旋转/平移的情况下可以使用“T。
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);
这可能并不完美,但是以这种方式进行工作为我解决了问题,并阻止了位图在整个商店中飞来飞去。 默认情况下,它也与您的图表不同,默认情况下也沿顺时针方向旋转,因此只需对反CW使用-angle。 不知道这是怎么回事,因为这段代码肯定无法为我带来理想的效果:
matrix.postTranslate(pivotPoint.x, pivotPoint.y);
matrix.postRotate(angle);
matrix.postTranslate(radius - (bitmap.getWidth()/2f), -bitmap.getHeight()/2f);
不能在这里看到逻辑有什么问题吗? 但是在我的情况下,位图在此处的视图中不可见。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.