- Right click on the
Fonts
folder in the Content project in Solution Explorer and select Add | New Item. - From the Add New Item dialog, select Sprite Font.
- Name the font Pericles36.spritefont. After adding the font, the
spritefont
file will open in the editor window. - In the
spritefont
file, change<Fontname>Kootenay</Fontname>
to<Fontname>Pericles</Fontname>
. - Change
<Size>14</Size>
to<Size>36</Size>
. - Add the following declaration to the Game1 class:
SpriteFont pericles36Font;
- Update the
LoadContent()
method of the Game1 class to loadspritefont
by adding:pericles36Font = Content.Load<SpriteFont>(@"Fonts\Pericles36");
Adding a SpriteFont to your game is very similar to adding a texture image. Since both are managed by the Content Pipeline, working with them is identical from a code standpoint. In fact, SpriteFonts are really just specialized sprite sheets, similar to what we used for our game pieces, and are drawn via the same SpriteBatch class we use to draw our sprites.
The .spritefont
file that gets added to your project is actually an XML document containing information that the Content Pipeline uses to create the .XNB
file that holds the bitmap information for the font when you compile your code. The .spritefont
file is copied from a template, so no matter what you call it, the XML will always default to 14 point Kootenay. In steps 4 and 5, we will edit the XML to generate 36 point Pericles
instead.
Just as with a Texture2D
, we declare a variable (this time a SpriteFont) to hold the Pericles
36 point font. The Load()
method of the Content
object is used to load the font.
Tip
SpriteFonts and extended characters
When a SpriteFont is built by the Content Processor, it actually generates bitmap images for each of the characters in the font. The range of characters generated is controlled by the <CharacterRegions>
section in the SpriteFont's XML description. If you attempt to output a character not covered by this range, your game will crash. You can avoid this by removing the HTML comment characters (<!--and -->) from around the <DefaultCharacter>
definition in the XML file. Whenever an unknown character is output, the character defined in <DefaultCharacter>
will be used in its place.