How to rotate a polygon around a point using Java?

I create a Canvas object (lines, vertices, a triangle, ...), and I would like to apply rotation around a point to them.

I can’t use the rotate () method of Canvas because the points are attached to the GeoPoint on the map, so if I use the rotate () method, all the maps rotate ...

The problem is that Canvas needs Point (int, int) and applying rotation creates a double due to the cos and sin functions. Therefore, when I apply rotation to all points, because you are double-binding to int, I have some kind of graphical problem that happens ...

So, I am looking for the best solution.

Here is my rotation code:

public Point rotatePoint(Point pt, Point center)
{
    this.angle = ((this.angle/180)*Math.PI);
    double cosAngle = Math.cos(this.angle);
    double sinAngle = Math.sin(this.angle);

    pt.x = center.x + (int) ((pt.x-center.x)*cosAngle-(pt.y-center.y)*sinAngle);
    pt.y = center.y + (int) ((pt.x-center.x)*sinAngle+(pt.y-center.y)*cosAngle);
    return pt;
}
+3
source share
3 answers

, . 0.5 , , , , - , 0,5, 1, . , , , (, ).

+1

pt.y. (pt.x , ). :

public Point rotatePoint(Point pt, Point center)
{
    this.angle = ((this.angle/180)*Math.PI);
    double cosAngle = Math.cos(this.angle);
    double sinAngle = Math.sin(this.angle);
    double dx = (pt.x-center.x);
    double dy = (pt.y-center.y);

    pt.x = center.x + (int) (dx*cosAngle-dy*sinAngle);
    pt.y = center.y + (int) (dx*sinAngle+dy*cosAngle);
    return pt;
}

:

public Point rotatePoint(Point pt, Point center, double angleDeg)
{
    double angleRad = (angleDeg/180)*Math.PI);
    double cosAngle = Math.cos(angleRad );
    double sinAngle = Math.sin(angleRad );
    double dx = (pt.x-center.x);
    double dy = (pt.y-center.y);

    pt.x = center.x + (int) (dx*cosAngle-dy*sinAngle);
    pt.y = center.y + (int) (dx*sinAngle+dy*cosAngle);
    return pt;
}
+5

Try the following:

public Point rotatePoint(Point pt, Point anchorPoint, double angleDeg) {                  
        double angleRad = Math.toRadians(angleDeg);
        double dx = (pt.x - anchorPoint.x); //x-cord. is transformed to origin
        double dy = (pt.y - anchorPoint.y); //y-cord. is transformed to origin

        double ptX = anchorPoint.x +  (dx * Math.cos(angleRad) - dy * Math.sin(angleRad));
        double ptY = anchorPoint.y +  (dx * Math.sin(angleRad) + dy * Math.cos(angleRad));


        return new Point((int) ptX, (int) ptY);
  }
0
source

All Articles