6

I have a rectangle: Rect r = new Rect();. I want to rotate the r object to 45 degrees. I checked for solutions and I found that it can be done with matrices:

Matrix m = new Matrix();
// point is the point about which to rotate.
m.setRotate(degrees, point.x, point.y);
m.mapRect(r);

The problem is that whey I pass the r to m.mapRect(r); it complains that r should be from type RectF. I managed to do it like:

RectF r2 = new RectF(r);
Matrix m = new Matrix();
// point is the point about which to rotate.
m.setRotate(degrees, point.x, point.y);
m.mapRect(r2);

But the problem is that I need object from type Rect not RectF . Because I am passing the r object to external class which is taking a Rect object.

Is there another way to rotate the rectangle r form type Rect except this method and without rotationg the whole canvas(canvas contains some other elements)?

Thank you in advance!

Best regards, Dimitar Georgiev

4

2 回答 2

11

以这种方式旋转矩形不会得到任何可用于绘图的东西。Rect 和 RectF 不存储任何有关旋转的信息。当您使用Matrix.mapRect()时,输出 RectF 只是一个新的非旋转矩形,其边缘接触您想要的旋转矩形的角点。

您需要旋转整个画布来绘制矩形。然后立即取消旋转画布以继续绘制,因此旋转其中包含其他对象的画布没有问题。

canvas.save();
canvas.rotate(45);
canvas.drawRect(r,paint);
canvas.restore();
于 2013-11-07T13:56:42.980 回答
1

如果您在矩阵上应用旋转,则另一种方法是不应该使用 mapRect。您应该找出代表每个矩形边缘的 4 个初始点,并改用 mapPoints。

float[] rectangleCorners = {
                            r2.left, r2.top, //left, top
                            r2.right, r2.top, //right, top
                            r2.right, r2.bottom, //right, bottom
                            r2.left, r2.bottom//left, bottom
                    };
Matrix m = new Matrix();
// point is the point about which to rotate.
m.setRotate(degrees, point.x, point.y);
m.mapPoints(r2);
于 2020-03-16T05:04:49.383 回答