Simple Text

Back to index

Using glutStrokeCharacter(), displaying text is easy. Its a bit limited in terms of font, and so on, but very simple to use. The function just displays one character, but here is an elaboration to display a string:

/**
     * Display a string of text.
     * The text is drawn in GLUT.STROKE_ROMAN font. Lighting is disabled,
     * and then restored to its initial sate. The text is scaled so that characters
     * are about 1 unit high.
     * @param gl The gl to draw it in
     * @param x     The x co-ordinate of the start
     * @param y     The y co-ordinate of the start
     * @param text  The text to display
     * @param color The color to draw it in
     * 
     */
    private void output(GL gl, float x, float y, String text, Color color) {
        char c;
        boolean lightingState;
        gl.glPushMatrix();
        gl.glTranslatef(x, y, 0);
        float height = glut.glutStrokeLengthf(GLUT.STROKE_ROMAN, "X");
        float factor = 1.0f / height;
        gl.glScaled(factor, factor, factor);
        gl.glTranslatef(x, y, 0);
        lightingState = gl.glIsEnabled(GL.GL_LIGHTING);
        gl.glDisable(GL.GL_LIGHTING);
        gl.glColor3d(color.getRed() / 255.0, color.getGreen() / 255.0, color.getBlue() / 255.0);
        gl.glLineWidth(2.0f);
        for (int offset = 0; offset < text.length(); offset++) {
            c = text.charAt(offset);
            glut.glutStrokeCharacter(GLUT.STROKE_ROMAN, c);
        }
        if (lightingState) {
            gl.glEnable(GL.GL_LIGHTING);
        }
        gl.glPopMatrix();
    }

and you would use this in display like:

output(gl,-6,0,"Hello World", Color.red);

Producing something like 1