create Rotated Shapes - Java java.lang

Java examples for java.lang:Math Geometry Shape

Description

create Rotated Shapes

Demo Code


import java.awt.*;
import java.awt.geom.*;
import java.awt.image.*;
import java.io.*;

public class Main{
    public static Shape[] createRotatedShapes(Shape original,
            double deltaDegrees) {
        int count = (int) (360 / deltaDegrees + 0.5);
        Shape[] polygons = new Shape[count];
        for (int i = 0; i < count; i++) {
            polygons[i] = rotateShape(original, i * deltaDegrees);
        }//from ww w. j  a  va2s .  c o m
        return polygons;
    }
    public static Shape rotateShape(Shape shape, double degrees) {
        Point center = shape.getCenter();
        Shape rotated = new Shape();
        int length = shape.size();
        for (int i = 0; i < length; i++) {
            Point p = shape.getPoint(i);
            double distance = getDistance(center, p);
            double angle = getAngle(center, p);
            rotated.add(movePoint(center, distance, degrees + angle));
        }
        return rotated;
    }
    public static double getDistance(Point p1, Point p2) {
        double deltaX = p2.x - p1.x;
        double deltaY = p2.y - p1.y;
        return Math.sqrt((deltaX * deltaX) + (deltaY * deltaY));
    }
    public static double getAngle(Point p1, Point p2) {
        double deltaX = p2.x - p1.x;
        double deltaY = p2.y - p1.y;
        return Math.atan2(deltaY, deltaX) * 180 / Math.PI;
    }
    public static Point movePoint(Point p, double distance, double angle) {
        // coordenadas da origem
        double x0 = p.x;
        double y0 = p.y;
        switch ((int) (angle + 0.5)) {
        case 0:
            return new Point(x0 + distance, y0);
        case 180:
            return new Point(x0 - distance, y0);
        case 90:
            return new Point(x0, p.y + distance);
        case 270:
            return new Point(x0, p.y - distance);
        default:
            // coordenadas da origem com transla??o no eixo x
            double x1 = x0 + distance;
            double y1 = y0;
            // coordenadas ap?s a rota??o
            double radians = Math.toRadians(angle);
            double cosA = Math.cos(radians);
            double sinA = Math.sin(radians);
            double x2 = x0 + ((x1 - x0) * cosA - (y1 - y0) * sinA);
            double y2 = y0 + ((x1 - x0) * sinA + (y1 - y0) * cosA);
            // devolver ponto rotacionado
            return new Point(x2, y2);
        }
    }
}

Related Tutorials