Java Android - 如何旋转矩形对象?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19837489/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Android - How to rotate Rect Object?
提问by chikito1990
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:
我有一个矩形: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);
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:
问题是我传递r
给m.mapRect(r);
它的乳清抱怨r
应该来自 type 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);
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.
但问题是我需要类型Rect
not 中的对象RectF
。因为我将r
对象传递给正在接受Rect
对象的外部类。
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)?
除了这种方法之外,还有其他方法可以旋转矩形r
表单类型Rect
而不旋转整个画布(画布包含一些其他元素)?
Thank you in advance!
先感谢您!
Best regards, Dimitar Georgiev
最好的问候, 迪米塔尔·格奥尔基耶夫
采纳答案by Tenfour04
Rotating a rectangle this way will not get you anything usable for drawing. A Rect and a RectF do not store any information about rotation. When you use Matrix.mapRect()
, the output RectF is just a new non-rotated rect whose edges touch the corner points of the rotated rectangle that you are wanting.
以这种方式旋转矩形不会为您提供任何可用于绘图的东西。一个 Rect 和一个 RectF 不存储任何关于旋转的信息。当您使用 时Matrix.mapRect()
,输出 RectF 只是一个新的非旋转矩形,其边缘接触您想要的旋转矩形的角点。
You need to rotate the whole canvas to draw the rectangle. Then immediately unrotate the canvas to continue drawing, so there is no issue with rotating the canvas that has other objects in it.
您需要旋转整个画布来绘制矩形。然后立即取消旋转画布以继续绘制,因此旋转包含其他对象的画布没有问题。
canvas.save();
canvas.rotate(45);
canvas.drawRect(r,paint);
canvas.restore();
回答by Zain Ali
Another way to do this if you are applying rotation on your matrix then you should not use mapRect. you should figure out the 4 initial points representing each rectangle edge and use mapPoints instead.
如果您在矩阵上应用旋转,则另一种方法是不要使用 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);