Use the SpriteBatch.DrawString
method for rendering text with XNA.
When you print text with System.Console.WriteLine
it is written to the standard output stream. The data in this stream is then presented through the console. Your game window takes no notice of this at all.
Text Rendering
It's fair to say that everything you draw to your game window consists of (textured) triangles. Text is no exception. A single character is rendered using a quad (rectangle), that again consists of 2 triangles.
The text XNA!
would be drawn using a total of 4 sprites (8 triangles), one sprite for every character:
Bitmap Font
Common font formats store the characters as vectors. For bitmap fonts (the kind of font usually used in games) the actual type face is stored in one or more bitmaps (textures). This method is much faster, as the character shapes themselves are already rasterized and only have to be sampled from the texture. The obvious drawback is, that the characters all come in a fixed size. You need one bitmap font per font face per size per weight.
This is a sprite map for the Arial font, size 20, standard weight:
For drawing a certain character, the renderer has to know where on the bitmap the character is located. As you can see in the image above, each character occupies a non overlapping rectangular area. The dimensions of those rectangles can be stored in an additional text or XML file.
For example, this could be a definition of the A
character for the sprite map above:
<char id="65" x="235" y="47" width="12" height="13" xoffset="0" yoffset="3" xadvance="11" page="0" />
id
is the ASCII value (A=65)x
andy
are the position of the top left cornerwidth
andheight
are the size of the rectanglexoffset
andyoffset
is the offset on screenxadvance
is the distance to the preceding characterpage
is the index of the bitmap that contains the character
Conclusion
Text rendering for games is not as trivial as one would assume. XNA greatly simplifies the process with the SpriteBatch
class. A summary of the steps involved:
- Convert a standard font to a bitmap font
- Load the font files in your game application
- Create the sprites for a given string
- Render the sprites to the screen
The font example was created with a free Bitmap Font Generator.