Drawing Text

Text is drawn on bitmap, with the use of a Font object. Although odl text drawing can sometimes feel rather archaic, it gets the job done. This may be revisited at a later date.

odl loads .ttf TrueType Font files for its fonts, and requires direct paths to those files - it cannot use system fonts, as this is not properly implemented in a cross-platform manner.

file-download
304KB
arial.ttf - Example font you can use.

To create (or reuse from an internal font cache) a font object, you'd use Font.Get():

Font f = Font.Get("arial", 12);

Font.Get() takes the filename (with or without .ttf; it searches both) and the size of the font.

To be able to draw text, a Bitmap object must be given a Font object. The bitmap does not need to be unlocked for this action. This can be done as follows:

Bitmap b = new Bitmap(100, 100);
b.Font = Font.Get("arial", 12);

Once the bitmap has been given a Font object, you can start drawing. The bitmap does need to be unlocked to be able to use DrawText() and DrawGlyph().

Sprite s = new Sprite();
s.Bitmap = new Bitmap(100, 100);
s.Bitmap.Unlock();

s.Bitmap.Font = Font.Get("arial", 14);
s.Bitmap.DrawText("Hello world!", Color.RED);

s.Bitmap.Lock();

In this example, I've omitted all optional DrawText() parameters: x, y, width, height, and DrawOptions. By default, DrawText() draws at (x, y) = (0, 0), with the width and height equal to the width and height of the text (so that there is no scaling involved), and anti-aliased.

Some fonts may benefit from being drawn without anti-aliasing. This example draws a slightly larger string of text, aliased, at (x, y) = (10, 20).

There are several draw options you can utilize, such as bold, italic, underline, and strikethrough.

DrawOptions can also determine the alignment of the text.

Text drawing always has a slight vertical offset for most letters to account for letters to are larger than usual. To account for that, you often want to offset your vertical positioning by a few pixels (e.g. -8). This varies per font type and per font size.

You can also draw text to fill an area.

You can also determine the size of a piece of text before actually drawing it. This can be used for background colors or mechanics like caret positioning. When you specify alignment via the DrawOptions, this is what it implicitly uses too.

circle-info

Bitmap.TextSize calls TextSize on its Font object; these do the exact same.

Some fonts use special characters to represent icons, such as the FontAwesome font. Using normal strings to draw these characters will produce very weird results, as these special characters are internally represented by multiple characters. Instead of using DrawText() for these, you'll want to use DrawGlyph(), which ensures it draws the correct character.

For instance, let's try drawing a camera icon. Its unicode value is 0x76, so we'll be drawing \x76.

Last updated