make Circle and return GeneralPath - Java 2D Graphics

Java examples for 2D Graphics:Path

Description

make Circle and return GeneralPath

Demo Code


//package com.java2s;

import java.awt.geom.*;

public class Main {
    public static void main(String[] argv) throws Exception {
        double xCenter = 2.45678;
        double yCenter = 2.45678;
        double r = 2.45678;
        int nPoints = 2;
        System.out.println(makeCircle(xCenter, yCenter, r, nPoints));
    }/*from w w w . j a v a 2  s .c om*/

    static public GeneralPath makeCircle(double xCenter, double yCenter,
            double r, int nPoints) {

        if (nPoints < 4)
            throw new RuntimeException("too few points. n=" + nPoints);

        GeneralPath gp = new GeneralPath();

        for (int i = 0; i < nPoints; i++) {
            double angle = i / (double) nPoints * Math.PI * 2;
            double x = r * Math.cos(angle) + xCenter;
            double y = r * Math.sin(angle) + yCenter;
            if (i == 0)
                gp.moveTo(x, y);
            else
                gp.lineTo(x, y);
        }

        gp.closePath();

        return gp;
    }
}

Related Tutorials