How to use SpriteFont in XNA

In this article I will be talking about how to use SpriteFont and draw string on XNA.


In this article I will be talking about how to use SpriteFont and draw string on XNA.

Lets start by creating a new project

1.gif
 
Add a SpriteFont in your Content Project.

2.gif
 
The SpriteFont should look like this:

<?xml version="1.0" encoding="utf-8"?>
<XnaContent xmlns:Graphics="Microsoft.Xna.Framework.Content.Pipeline.Graphics">
  <Asset Type="Graphics:FontDescription">
   <FontName>Kootenay</FontName>
   <Size>14</Size>
   <Spacing>0</Spacing>
   <UseKerning>true</UseKerning>
   <Style>Regular</Style>
   <CharacterRegions>
      <CharacterRegion>
        <Start>&#32;</Start>
        <End>&#126;</End>
      </CharacterRegion>
    </CharacterRegions>
  </Asset>
</XnaContent>

Add a SpriteFont and Vector2 variable:

SpriteFont Font1;
Vector2 FontPos;

In your LoadContent function add:

spriteBatch = new SpriteBatch(GraphicsDevice);
Font1 = Content.Load<SpriteFont>("OurFont");
FontPos = new Vector2(graphics.GraphicsDevice.Viewport.Width / 2,graphics.GraphicsDevice.Viewport.Height / 2);

OurFont is the name of the SpriteFont Item added from "Add->New Item"

Remember to call its asset name when you need to

And Update your Draw Function as seen below:

protected override void Draw(GameTime gameTime)
{
  GraphicsDevice.Clear(Color.CornflowerBlue);
  spriteBatch.Begin();
  string output = "Hello World";
  Vector2 FontOrigin = Font1.MeasureString(output) / 2;
  spriteBatch.DrawString(Font1, output, FontPos, Color.Black,
                0, FontOrigin, 1.0f, SpriteEffects.None, 0.5f);
  spriteBatch.End();
  base.Draw(gameTime);
}

And what we see is a text drawn on the center of the window:

3.gif 

Adding a Font and drawing string on the screen is so easy as you can see.

The following list of fonts are installed by XNA Game Studio and are redistributable.

The Supported fonts are:

Kootenay(Kooten.ttf)
Lindsey(Linds.ttf)
Miramonte(Miramo.ttf, Bold Miramob.ttf (bold))
Pericles(Peric.ttf, Pericl.ttf (bold))
Pescadero(Pesca.ttf, Pescab.ttf (bold))

These OpenType fonts, created by Ascender Corporation and licensed by Microsoft, are free for you to use in your XNA Game Studio game. You may redistribute these fonts in their original format as part of your game. These fonts were previously available only on the XNA Creators Club Online Web site.