以一定角度绘制矩形

时间:2012-12-21 14:44:16

标签: java graphics

Java中用于绘制矩形的方法是什么,具有以下内容:

  • 广场中心的坐标
  • 矩形与垂直方向的角度,单位为度

2 个答案:

答案 0 :(得分:4)

以您建议的方式绘制矩形,您需要使用类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);

答案 1 :(得分:0)

对于第一点,你可以通过使用距离公式(int)Math.sqrt((x1 - x2)*(x1 - x2) + (y1 - y2)*(y1 - y2));除以2来计算出方形中心的坐标。你可以为宽度和高度做到这一点。我不太了解Java绘图,根据您的问题提供更好的答案,但我希望有所帮助。

对于第二个,你需要创建一个多边形吗?