XNA Displaying Text

In order to display text to the screen we need to create a font and use the SpriteBatch DrawString function.

Creating a font

Fonts in XNA are handled by the content pipeline like other game assets. They are described via an XML file. To add one right click on Content in the solution explorer and select Add / New Item and then click on Sprite Font and Add. A new file called SpriteFont1.spritfont is added to your project and opened. This is an XML file and is fairly straight forward to alter - just look at the comments for each entry.

We need to create a SpriteFont object to handle our font so add a variable to your class:

SpriteFont spriteFont;

In your LoadContent function we instantiate an object of this class using the Content.Load function we used previously to load a texture in XNA start. This time we say we want a SpriteFont type:

Rendering text

To draw text we use the SpriteBatch object - the same one we used for drawing our textures in XNA start. In between the SpriteBatch begin and end calls (make sure you only ever have one pair of begin and end calls i.e. do all 2D stuff in between them).

The Draw function has many overloads (6), the one used here just takes the font name, the text to be drawn, position and colour but others also allow rotation,  origin, scale and depth to be set.

spriteBatch.DrawString(spriteFont, "Hello World", Vector2.Zero, Color.Cyan);

© 2004-2016 Keith Ditchburn