以一定角度绘制矩形

APe*_*son 2 java graphics

在Java中,给定以下条件的矩形是什么方法:

  • 正方形中心的坐标
  • 矩形与垂直线的夹角,以度为单位

Dun*_*nes 5

按照建议的方式绘制矩形,您需要使用类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);
Run Code Online (Sandbox Code Playgroud)