Rotate Rectangle in Java(Java中的旋转矩形)
问题描述
我需要创建围绕其中心旋转的矩形(因此它们不需要平行于坐标系的轴).所以基本上每个矩形都可以由 center-X、center-Y、width、height 和 定义>角度.然后我想做的是计算某些点是否包含在这些矩形中(因此不涉及绘图).我想我不能使用 Rectangle2D 类,因为这些矩形总是平行于坐标系的 x 和 y 轴.是通过编写我自己的矩形类来获得此功能的唯一方法,还是我可以使用现有的任何东西(类似于 Rectangle2D)?
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, height and 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?
推荐答案
旋转所有要测试的点,像米海一样使用 Rectangle2D 的 contains(Point) 方法.
Rotate all the points you want to test and use contains(Point) method of the Rectangle2D as Mihai did.
但如果你真的想旋转矩形,你可以这样做(这是整数版本,但也许你也可以用 Rectangle2D 来做 :)).
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 :)).
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));
}
}
这篇关于Java中的旋转矩形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java中的旋转矩形
基础教程推荐
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
