在 Java 中旋转矩形
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4145609/
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
Rotate Rectangle in Java
提问by gaussd
I need to create rectangles that are rotated around their center (so they don't need to be parallel to the axes of the coordinate system). So basicelly each rectangle can be defined by center-X, center-Y, width, heightand angle. What I want to do then is to perform calculations on whether certain points are contained in these rectangles or not (so no drawing will be involved). I guess I cant use the Rectangle2D
class because these rectangles will always be parallel to the x and y-axis of the coordinate system. Is the only way to get this functionality by writing my own rectangle class or is there anything existing (similar to Rectangle2D
) I can use?
我需要创建围绕其中心旋转的矩形(因此它们不需要与坐标系的轴平行)。所以基本上每个矩形都可以由center-X、center-Y、width、height和angle 定义。然后我想做的是对这些矩形中是否包含某些点进行计算(因此不涉及绘图)。我想我不能使用这个Rectangle2D
类,因为这些矩形总是平行于坐标系的 x 和 y 轴。是通过编写我自己的矩形类来获得此功能的唯一方法还是Rectangle2D
我可以使用现有的任何东西(类似于)?
回答by dacwe
Rotate all the points you want to test and use contains(Point) method of the Rectangle2D as Mihai did.
旋转所有要测试的点,并像 Mihai 一样使用 Rectangle2D 的 contains(Point) 方法。
But if you really want to rotate the rectangles you can do it like this (this is the integer version but probably you can do it with Rectangle2D aswell :)).
但是如果你真的想旋转矩形,你可以这样做(这是整数版本,但可能你也可以用 Rectangle2D 来做:))。
public class TestRotate {
public static void main(String... args) {
Rectangle r = new Rectangle(50, 50, 100, 100);
Point check = new Point(100, 151); // clearly outside
System.out.println("first: " + r.contains(check));
AffineTransform at = AffineTransform.getRotateInstance(
Math.PI/4, r.getCenterX(), r.getCenterY());
Polygon p = new Polygon();
PathIterator i = r.getPathIterator(at);
while (!i.isDone()) {
double[] xy = new double[2];
i.currentSegment(xy);
p.addPoint((int) xy[0], (int) xy[1]);
System.out.println(Arrays.toString(xy));
i.next();
}
// should now be inside :)
System.out.println("second: " + p.contains(check));
}
}
回答by Mihai
You can use Rectangle2D to check for containment, if instead of rotating your rectangle by an angle, say, counterclockwise, you rotate each of the points you need to check by the same angle clockwise, relative to the center of the rectangle. Something like
您可以使用 Rectangle2D 检查包含情况,如果不是将矩形旋转一个角度,例如逆时针旋转,而是相对于矩形的中心顺时针旋转您需要检查的每个点相同的角度。就像是
double dx = point.x - rectangleCenter.x;
double dy = point.y - rectangleCenter.y;
double newX = rectangleCenter.x - dx*Math.cos(angle) + dy*Math.sin(angle);
double newY = rectangleCenter.x - dx*Math.sin(angle) - dy*Math.cos(angle);