Jasper R. Jasper R. -4 years ago 118
Java Question

Java: AffineTransform rotate Polygon, then get its points

I'd like to draw a Polygon and rotate it with AffineTransform like so.

float theta = 90;
Polygon p = new Polygon(new int[]{0, 4, 4, 0}, new int[]{0, 0, 4, 4}, 4);
AffineTransform transform = new AffineTransform();
transform.rotate(Math.toRadians(theta), p.xpoints[0], p.ypoints[0]);
Shape transformed = transform.createTransformedShape(p);

However, then I'd like to be able to access the points (transformed.xpoints[0]) in the same way I did as a Polygon. One way to look at this would be transforming the Shape into a Polygon--but as far as I know this isn't possible.

What's the best option?

As a sidenote: this is an exercise in creating a fractal tree made of 4-sided Polygons (rectangles). I've chosen to use Polygons in order to anchor branches to the top left and top right points, respectively. If this is needlessly complicated, let me know.

Answer Source

You can use the AffineTransform to transform the individual points as well, like so:

Point2D[] srcPoints = new Point2D[] { new Point(0, 0), new Point(4, 0), new Point(4, 4), new Point(4, 0) };
Point2D[] destPoints = new Point2D[4];
transform.transform(srcPoints, 0, destPoints, 0, 4);

The resulting destPoints array then looks like this:

[Point2D.Float[-0.0, 0.0], Point2D.Float[-0.0, 4.0], Point2D.Float[-4.0, 4.0], Point2D.Float[-0.0, 4.0]]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download