Font rendering

Overview

This sample demonstrates the basic capabilities of the font renderer, which can be used to render high-quality, 2d text on a color buffer.

Requirements

The font renderer depends on OpenGL 1.1, but takes advantage of higher OpenGL versions to improve quality and/or speed.

Usage

To use the font renderer, create and store a TextPrinter instance.

The Print method renders a System.String using the specified System.Drawing.Font and System.Drawing.Color. You can optionally specify a layout rectangle, one or more layout flags (e.g. right-to-left or vertical) and one or more TextPrinterFlags (e.g. no cache).

The Measure method measures the bounding box of each character (also called 'glyph extents') and the bounding box of the whole string. It can be used to get accurate data for laying out GUI elements or rendering a caret.

The Begin and End methods can be used to setup and restore a pixel-perfect, resolution dependent, orthographic projection matrix on the current OpenGL context. This matrix matches the typical 2d coordinate system of the native font rendering libraries (origin on the top-left corner of the screen) and ensures that text drawn through OpenTK will look identical to native text.

A typical usage scenario looks like this:

using System;
using System.Drawing;
using OpenTK.Graphics;
...
Font font = new Font(FontFamily.GenericSansSerif, 16.0);
ITextPrinter printer = new TextPrinter();
...
printer.Begin();
printer.Print(frames_per_second.ToString(), font, Color.SpringGreen);
printer.End();

If you wish to specify a custom projection matrix, do not call TextPrinter.Begin or TextPrinter.End and scale the text by the inverse of your viewport Width and Height, multiplied by two. For example:

GL.MatrixMode(MatrixMode.Projection);
GL.LoadIdentity();
GL.Ortho(-1, 1, -1, 1, -1, 1);
GL.MatrixMode(MatrixMode.Modelview);
GL.LoadIdentity();
GL.Scale(2.0 / Width, 2.0 / Height, 1.0);

printer.Print(frames_per_second.ToString(), font, Color.SpringGreen);