Android - 如何旋转Rect对象?

chi*_*990 4 java android android-canvas

我有一个矩形: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);
Run Code Online (Sandbox Code Playgroud)

问题是乳清我传递rm.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);
Run Code Online (Sandbox Code Playgroud)

但问题是,我需要从类型的对象Rect不是RectF.因为我将r对象传递给正在接受Rect对象的外部类.

是否有另一种方法来旋转矩形r窗体类型,Rect除了这个方法,并且没有旋转整个画布(画布包含一些其他元素)?

先感谢您!

此致,Dimitar Georgiev

Ten*_*r04 9

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

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

canvas.save();
canvas.rotate(45);
canvas.drawRect(r,paint);
canvas.restore();
Run Code Online (Sandbox Code Playgroud)