XNA 4.0 Game Development by Example: Beginner's Guide
上QQ阅读APP看书,第一时间看更新

Time for action – add SpriteFonts to Game1

  1. Right click on the Fonts folder in the Content project in Solution Explorer and select Add | New Item.
  2. From the Add New Item dialog, select Sprite Font.
  3. Name the font Pericles36.spritefont. After adding the font, the spritefont file will open in the editor window.
  4. In the spritefont file, change <Fontname>Kootenay</Fontname> to <Fontname>Pericles</Fontname>.
  5. Change <Size>14</Size> to <Size>36</Size>.
  6. Add the following declaration to the Game1 class:
    SpriteFont pericles36Font;
  7. Update the LoadContent() method of the Game1 class to load spritefont by adding:
    pericles36Font = Content.Load<SpriteFont>(@"Fonts\Pericles36");

What just happened?

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.

Score display

Displaying the player's score with our new SpriteFont is simply a matter of calling the SpriteBatch.DrawString() method.