draw Circle by opengl - Java javax.media.opengl

Java examples for javax.media.opengl:GL

Description

draw Circle by opengl

Demo Code


import java.awt.Color;
import javax.media.opengl.GL;

public class Main{
    public static void drawCircle(GL gl, Color colorOutside,
            Color colorInside, Color stroke, Point center, int radius) {
        double increment = 2 * Math.PI / 50;

        // Draw a bunch of triangles
        for (double angle = 0; angle < 2 * Math.PI; angle += increment) {
            float x1 = center.x + (float) Math.cos(angle) * radius;
            float y1 = center.y + (float) Math.sin(angle) * radius;
            float x2 = center.x + (float) Math.cos(angle + increment)
                    * radius;/*from w  w w . ja va  2 s . c  om*/
            float y2 = center.y + (float) Math.sin(angle + increment)
                    * radius;

            gl.glBegin(GL.GL_TRIANGLES);
            setColor(gl, colorInside);
            gl.glVertex2d(center.x, center.y);
            setColor(gl, colorOutside);
            gl.glVertex2f(x1, y1);
            gl.glVertex2f(x2, y2);
            gl.glEnd();
        }

        gl.glBegin(GL.GL_LINE_LOOP);

        // Highlight the stroke edge of each triangle
        for (double angle = 0; angle < 2 * Math.PI; angle += increment) {
            float x1 = center.x + (float) Math.cos(angle) * radius;
            float y1 = center.y + (float) Math.sin(angle) * radius;
            float x2 = center.x + (float) Math.cos(angle + increment)
                    * radius;
            float y2 = center.y + (float) Math.sin(angle + increment)
                    * radius;

            setColor(gl, stroke);
            gl.glVertex2f(x1, y1);
            gl.glVertex2f(x2, y2);
        }

        gl.glEnd();
    }
    public static void drawCircle(GL gl, Color color, Color stroke,
            Point center, int radius) {
        drawCircle(gl, color, color, stroke, center, radius);
    }
    public static void setColor(GL gl, Color color) {
        if (color != null) {
            float red = color.getRed() / 255f;
            float green = color.getGreen() / 255f;
            float blue = color.getBlue() / 255f;
            float alpha = color.getAlpha() / 255f;

            gl.glColor4f(red, green, blue, alpha);
        }
    }
}

Related Tutorials