XNA: Using Fonts in XNA 3.1

XNA 3.1

No difference in how to use Fonts in XNA 3.1 over XNA 2.0.  If you already know how to use text in your project, this won’t be a big help to you.  This article was written to try to look a little smarter than my previous blog may have made me look.

Using text in your XNA project

Using the previous Blog approach, was simple, but not elegant. 

It would be better to add text that indicates whether or not SpriteBatch is an abstract class or a base class.

In this case you will need to add an existing content resource to the project.  The image below shows you how to add the spritefont material to the content folder.  There is a link that gets you to a very clear way to implement text in your game project.  Over future blogs we will go over how to add text, scoring and so forth to your game. 

Follow the article on MSDN:

Use the diagram to the right to add the existing content templates, in this case Sprite Font.

Ok, now you have added the content resources what do you do?

First you have to construct the objects from the base or abstract classes, the objects need to build the fonts/letters and the location of the fonts/letters

construct/instantiate a SpriteFont object and in this case the object’s name is Font1

You will also need a way to place it on the gameboard. 

The way you put it on the game board is through the construction/instantiation of the class Vector2, and the object that is constructed is named FontPos.

SpriteFont is a sealed class which is a member of the Microsoft.Xna.Framework.Graphics, which is in the file named:

public class Game1 : Microsoft.Xna.Framework.Game
       GraphicsDeviceManager graphics;
       SpriteBatch spriteBatch;

       //Add the two lines below

       SpriteFont Font1;
       Vector2 FontPos;



Your code should look like:


Later in the code, the FontPos will be used to determine the HEIGHT and WIDTH of the pixels that make up the text that are being written on the screen

In your test of whether or not spriteBatch is abstract or a base class, this test will function to change the screen red if spriteBatch is a class, and it will stay blue if it isn’t and write the message on the screen.


Comments (0)

Skip to main content