XNA and GIS (3) - Using Fonts

The recent release of Microsoft’s XNA Game Studio Refresh offers one important new feature: font support. If we want to build any sort of mapping application, text is an absolute necessity. So here is a quick tutorial of how to incorporate font into a XNA program. For a complete description, check out the Game Studio documentation.

Font Preparation

Font is treated similar to any other 2D sprite in XNA except for the source of the texture. Instead of relying on graphics, XNA obtains the font from the font files already installed on your computer. Examples include Times New Roman, Courier New, and Arial.

Preparing to use a font is simple. In any XNA program, right-click in the Solution Explorer and select Add New Item. Scroll to the bottom and select the Sprite Font icon:

xna_spritefont


This generates a XML configuration file that provides the information that XNA needs to import that font file into the Content Pipeline and thus have the ability to be drawn in the program. For example, to use Courier New font, the first element should be:

<FontName>Courier New</FontName>

Other elements in the XML file that contain information on font size, spacing, and style can be changed accordingly.

Using the Font

Several lines of code need to be added once the configuration file is setup. First define a SpriteFont object:

SpriteFont courierNew;

Then in the LoadGraphicsContent method, create a font object using the asset name of the configuration file:

courierNew = content.Load("Content\\Font\\ConsoleFont");

Finally, use the DrawString method of a SpriteBatch object to draw the font on screen:

spriteBatch.DrawString(courierNew,"Insert Text String", new Vector2(5,5), Color.Red);

There are additional parameters that allow for the text to be rotated or scaled but most of the time we just need a string, the location, and a color.

Next time we will demonstrate a simple application using font. Our focus will be on creating a console-type application that will eventually be part of a larger mapping application.

Comments are closed.