Trying to use GraphicsContext method Public void fill and strokepolygon in order to draw a regular polygon

174 views Asked by At

I created a draw method in order to draw a regular hexagon using the fillPolygon and strokePolygon methods in java.Currently I am stuck trying to figure out how to get the six x and y coordinates needed to draw the regular polygon. Would anyone be able to help me? Here is the structure of fill polygon:

Public void fillPolygon(double[] xPoints,
                        double[] yPoints,
                        int nPoints)

Fills a polygon with the given points using the currently set fill paint. A null value for any of the arrays will be ignored and nothing will be drawn. This method will be affected by any of the global common, fill, or Fill Rule attributes as specified in the Rendering Attributes Table.

Parameters: xPoints - array containing the x coordinates of the polygon's points or null. yPoints - array containing the y coordinates of the polygon's points or null. nPoints - the number of points that make the polygon.

1

There are 1 answers

0
CryptoFool On

I wrote you a class to do what you need:

public class Coordinate {

    double x;
    double y;

    public Coordinate(double x, double y) {
        this.x = x;
        this.y = y;
    }

    private static Coordinate fromPolar(double magnitude, double angle) {
        double flippedAngle = Math.PI/2 - angle;
        return new Coordinate(magnitude * Math.cos(flippedAngle),
                magnitude * Math.sin(flippedAngle));
    }

    public static Coordinate[] regularPolygonCoordinates(int sides, double radius) {
        Coordinate[] r = new Coordinate[sides];
        for (int i = 0 ; i < sides ; i++)
            r[i] = fromPolar(radius, 2.0 * Math.PI * i / sides);
        return r;
    }

    public static void main(String[] args) {
        Coordinate[] hexagon = regularPolygonCoordinates(6, 1);
        for (Coordinate coord : hexagon) {
            System.out.printf("%f,%f\n", coord.x, coord.y);
        }
    }
}

Result for hexagon of radius 1.0:

0.000000,1.000000
0.866025,0.500000
0.866025,-0.500000
0.000000,-1.000000
-0.866025,-0.500000
-0.866025,0.500000

You can either put this code in your code and call it every time you need coordinates, or you can just hard-code the above coordinates for a Unit Hexagon into your code and then scale all of the coordinates by whatever radius you want your hexagon to have.

If you want to do the latter, you wouldn't really even need this code. I found this cool Polygon Vertex Calculator online that will give you the coordinates for any 'agon.

If you do want to use this code directly, you can get the two separated arrays of vertexes like this:

double[] xPoints = new double[6];
double[] yPoints = new double[6];
for (int i = 0 ; i < 6 ; i++) {
    xPoints[i] = hexagon[i].x;
    yPoints[i] = hexagon[i].y;
}