以角度绘制矩形

3

在Java中,有一种方法可以根据以下信息绘制矩形:

  • 正方形中心的坐标
  • 矩形相对于竖直方向的角度(以度为单位)

你想在哪里绘制矩形?在Swing应用程序中吗?在JSP中还是其他地方? - Pradeep Simha
画一个矩形,然后通过 AffineTransform 进行旋转。 - moonwave99
@J.Steen 实际上不是这样的 :) - APerson
2个回答

6
要按照您所建议的方式绘制一个矩形,您需要使用 AffineTransform 类。该类可用于以各种方式转换形状。要执行旋转,请使用:
int x = 200;
int y = 100;
int width = 50;
int height = 30;
double theta = Math.toRadians(45);

// create rect centred on the point we want to rotate it about
Rectangle2D rect = new Rectangle2D.Double(-width/2., -height/2., width, height);

AffineTransform transform = new AffineTransform();
transform.rotate(theta);
transform.translate(x, y); 
// it's been while, you might have to perform the rotation and translate in the
// opposite order

Shape rotatedRect = transform.createTransformedShape(rect);

Graphics2D graphics = ...; // get it from whatever you're drawing to

graphics.draw(rotatedRect);

0

首先,您可以使用距离公式计算正方形中心的坐标:(int)Math.sqrt((x1 - x2)*(x1 - x2) + (y1 - y2)*(y1 - y2)); 然后将其除以2。对于宽度和高度也可以这样做。根据您问题中提供的信息,我不太了解Java绘图,无法给出更好的答案,但希望这能有所帮助。

至于第二个问题,您只需要创建一个多边形即可,是吗?


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接