Skip to main content

Rotating Points and/or Polygons around a center Point

2 replies [Last post]
dmarcum
Offline
Joined: 2010-02-16

After searching for what seems like hours to find a simple solution to this problem...and yes I know that AffineTransform can do this, but I knew there was a lot simpler/faster solution and one that doesn

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
flar
Offline
Joined: 2003-06-11

I wanted to point out some other techniques which might also meet your needs.

The simplest would be to use:

g2.rotate(radians, centerx, centery);
g2.draw(untransformed_object);

This doesn't create any new objects at the application level, though some pipelines might create new objects internally. Have you investigated the performance of this technique to show that it isn't fast enough (or that it creates too much garbage in practice) for your needs?

Another solution for "doing it manually" as you do, but relying on standard objects to do your work for you would be to use:

private AffineTransform scratchAT = new AffineTransform();
private double origpoints[] = new double[npoints * 2];
private double txpoints[] = new double [npoints * 2];
... then in paintComponent()...
at.setToRotation(radians, centerx, centery);
at.transform(origpoints, 0, txpoints, 0, npoints);
... then either use drawLine: ...
for (int i = 2; i < txpoints.length; i += 2) {
g2.setColor(...);
g2.drawLine((int) txpoints[i-2], (int) txpoints[i-1], (int) txpoints[i], (int) txpoints[i+1]);
}
... or use a temp shape which would allow sub-pixel rendering positions: ...
for (int i = 2; i < txpoints.length; i += 2) {
g2.setColor(...);
templine.setLine(txpoints[i-2 through i+1]);
g2.draw(templine);
}

I'm not sure if either of those techniques meet your needs, but they might involve less custom code on your part.

It is important to note that your solution and the second solution above do not allow for quality line joins at the vertices should the rendering ever be scaled up (such as when it is printed). To make sure that the line joins look nice under a scale, you should use the first solution above.

Message was edited by: flar

dmarcum
Offline
Joined: 2010-02-16

oops...some of the code got cut off...replace the end of paintComponent method with this...

try
{
Thread.sleep(20);
}
catch (Exception exception)
{
// Ignore
}

repaint();
}

private double getAngle360(double x1, double y1, double x2, double y2)
{
double angle = Math.toDegrees(Math.atan2(y2 - y1, x2 - x1));
if (angle < 0) angle = 180 + (180 - -angle);
angle += 90;
if (angle >= 360) angle -= 360;
return angle;
}