简体   繁体   中英

How to rotate a polygon about a point

I am using Java's Graphics2D libraries to draw various shapes with lines connecting them together. Some of these lines will need an arrow head at the end of the line. The shapes can be in any position so the angle of the arrow will change.

So far my code draws the arrow and rotates it except it isn't ever at the right angle or in the right location. When I move my shapes around the screen the arrow appears to orbit the shape it is meant to point to. (coord x2, y2)

private static void drawArrow(Graphics2D g, int size, int x1, int y1, int x2, int y2) {
    double dx = x2 - x1, dy = y2 - y1;
    double theta = Math.atan2(dy, dx);
    AffineTransform at = AffineTransform.getTranslateInstance(x2, y2);
    Polygon p = new Polygon();
    p.addPoint(0, 0);
    p.addPoint(size, 0 - size);
    p.addPoint(0 - size, 0 - size);
    at.rotate(theta, x2, y2);
    java.awt.Shape shape = at.createTransformedShape(p);
    g.fill(shape);
}

int size - the size of the arrow divide 2.

int x1, y1 - first shapes x and y coords. (centre of shape)

int y2, x2 - second shapes x and y coords. (centre of shape)

You can see what I mean in these pictures: 例子1

例子2

I have a feeling I'm close to getting this because it seems to orbit the shape perfectly, which suggests to me it is just not rotating at the right angle or point.

First you need to get the angle at which the line is, so start by noting the start of the line (the one touching the top box) as the origin. The angle can be found using this formula: tan(theta) = (y/x) y being how much you went down, x being how much you went to the left (both from the origin, and left/down being your axis direction which is default usually in java for outputs)

theta = Math.atan(x/y);

then you apply the angle of rotation to your triangle with an offset ofcourse to get it in the right direction:

at.rotate(theta + offset);

You can get the offset by trial and error. Keep in mind cos/sin/tan use radians

Math.toRadians(double angleInDegrees)
Math.toDegrees(double angleInRadians)

also you should read how methods are used on the java docs for AffineTransform @ docs

the .rotate(double angle, double x, double y) is used to rotate around a point at (x,y)
use .rotate(double angle) instead. and then just translate the triangle back to the new points

The rotation is made with origin (0,0)

You have 2 ways:

1.- Calculate rotation in the origin of the shape.

2.- Move the shape to (0,0) rotate and then return to current location.

I don't have the code right now, but it's easy :) I already make it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM