Android-如何旋转Rect对象?

问题描述 投票:5回答:2

我有一个矩形:Rect r = new Rect();。我想将r对象旋转到45度。我检查了解决方案,发现可以用矩阵来完成:

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

问题是乳清我将r传递给m.mapRect(r);,它抱怨r应该来自RectF类型。我设法做到了:

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);

但是问题是我需要类型Rect而不是RectF的对象。因为我将r对象传递给采用Rect对象的外部类。

除了此方法之外,还有没有其他方法可以旋转矩形r表单类型Rect,并且不旋转整个画布(画布包含其他元素)?

谢谢你!

最诚挚的问候,Dimitar Georgiev

java android android-canvas
2个回答
9
投票

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

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

canvas.save();
canvas.rotate(45);
canvas.drawRect(r,paint);
canvas.restore();

0
投票

如果在矩阵上应用旋转,则另一种方法,则不应使用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);
© www.soinside.com 2019 - 2024. All rights reserved.