Add code for rotating a vertex around certain point (#15683)

Co-authored-by: rajatgarg <rajatgarg@adobe.com>
This commit is contained in:
Rajat Garg 2024-01-19 06:07:35 +05:30 committed by GitHub
parent b38e72cd5a
commit 82d2112665
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 57 additions and 0 deletions

View File

@ -0,0 +1,26 @@
package com.baeldung.math.rotatevertex;
import java.awt.geom.AffineTransform;
import java.awt.geom.Point2D;
public class VertexRotation {
public static Point2D.Double usingOriginAsRotationPoint(Point2D.Double vertex, Point2D.Double rotationPoint, double angle) {
double translatedToOriginX = vertex.x - rotationPoint.x;
double translatedToOriginY = vertex.y - rotationPoint.y;
double rotatedX = translatedToOriginX * Math.cos(angle) - translatedToOriginY * Math.sin(angle);
double rotatedY = translatedToOriginX * Math.sin(angle) + translatedToOriginY * Math.cos(angle);
double reverseTranslatedX = rotatedX + rotationPoint.x;
double reverseTranslatedY = rotatedY + rotationPoint.y;
return new Point2D.Double(reverseTranslatedX, reverseTranslatedY);
}
public static Point2D.Double usingAffineTransform(Point2D.Double vertex, Point2D.Double rotationPoint, double angle) {
AffineTransform affineTransform = AffineTransform.getRotateInstance(angle, rotationPoint.x, rotationPoint.y);
Point2D.Double rotatedVertex = new Point2D.Double();
affineTransform.transform(vertex, rotatedVertex);
return rotatedVertex;
}
}

View File

@ -0,0 +1,31 @@
package com.baeldung.math.rotatevertex;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.awt.geom.Point2D;
import org.junit.jupiter.api.Test;
public class VertexRotationUnitTest {
@Test
void givenRotationPoint_whenUseOrigin_thenRotateVertex() {
Point2D.Double vertex = new Point2D.Double(2.0, 2.0);
Point2D.Double rotationPoint = new Point2D.Double(0.0, 1.0);
double angle = Math.toRadians(45.0);
Point2D.Double rotatedVertex = VertexRotation.usingOriginAsRotationPoint(vertex, rotationPoint, angle);
assertEquals(0.707, rotatedVertex.getX(), 0.001);
assertEquals(3.121, rotatedVertex.getY(), 0.001);
}
@Test
void givenRotationPoint_whenUseAffineTransform_thenRotateVertex() {
Point2D.Double vertex = new Point2D.Double(2.0, 2.0);
Point2D.Double rotationPoint = new Point2D.Double(0.0, 1.0);
double angle = Math.toRadians(45.0);
Point2D.Double rotatedVertex = VertexRotation.usingAffineTransform(vertex, rotationPoint, angle);
assertEquals(0.707, rotatedVertex.getX(), 0.001);
assertEquals(3.121, rotatedVertex.getY(), 0.001);
}
}