'Drawing rectangles at an angle

What is a method in Java that draws a rectangle given the following:

  • The coordinates of the center of the square
  • The angle of the rectangle from vertical, in degrees


Solution 1:[1]

To draw a rectangle in the way you suggest you need to use the class AffineTransform. The class can be used to transform a shape in all manner of ways. To perform a rotation use:

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);

Solution 2:[2]

For the first point, you can just figure out the coordinates of the center of the square by using a distance formula, (int)Math.sqrt((x1 - x2)*(x1 - x2) + (y1 - y2)*(y1 - y2)); them divide by 2. you can do this for the width and height. I don't know enough about Java draw to give you better answers based on what was in your question but I hope that helps.

For the second, you would need to just create a polygon right?

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 nomnomnomplant