University of the West of England, Bristol

Department of Computer Science and Creative Technologies


C# XNA Worksheet 3 - Writing Text using a Sprite Font

C# 2010 - XNA Version 4


Learning Aims

This worksheet shows you how to import a special object called a Sprite Font into a game, and then how to use it to write text onto the game window.

When you've completed this worksheet, you should be able to:

To get the most out of this worksheet you should do the following:


If You Get Interrupted

If you are unable to finish any of these worksheets in one go, then this is what you should do to make sure that you can resume it from the point you finished, without having to start from scratch:


Practical Steps- What You Have to Do

Before Starting

This worksheet assumes that you've already completed worksheets 1 and 2, and builds on the knowledge that you have previously acquired. If you haven't finished worksheets 1 and 2 you should do so now.

Getting Started

  1. Start XNA Game Studio and create a NEW Windows Game project. You should name the project SpriteFontProject

Loading the Sprite Font into the Content Section

A sprite font is a sprite which is created from one of the fonts installed on the system. Just like any sprite, it has to be created in the Content section of the project explorer, and then loaded into the C# application using this.Content.Load<>.

Unlike a normal sprite, we don't need a previously created image - just one of the fonts already installed on the system.

  1. Find the Content section of the Solution Explorer - Right click on SpriteFontProjectContent(Content) and select: Add > New Item...
  2. From the selection box, click ONCE on Sprite Font (circled in red), change the name to Arial16.spritefont, and then click on OK:
  3. When you have done this, you should see a tab at the top of the screen for the Arial16 spritefont. Click on this tab.:

    You should see an XML document which has entries for the font name, font size and several other parameters. If you can't see then go to the Content section of the Solution Explorer and double click on Arial16.spritefont.

  4. Scroll down the file until you find the font name section. Change the font name to Arial and the font size to 16:

    Note: As you probably know, Arial is a standard font installed in Windows. We named the sprite font "Arial16" since we use the 16 point size. I recommend that you name all your sprite fonts in a similar manner

Using the Sprite Font

Sprite fonts are used a in a similar fashion to normal sprites. We must load them into the program in the LoadContent() method, and we can draw a string using the spriteBatch.DrawString() method.

  1. Add the following new field to the Game1.cs file:
      SpriteFont arial16;
      
  2. Go to the LoadContent() method and add the following statement:
     arial16 = this.Content.Load<SpriteFont>("Arial16");
      
  3. Go to the Draw() method put in the following code:
      spriteBatch.Begin();
    
      Vector2 position = new Vector2(100, 100);
      spriteBatch.DrawString(arial16, "Hello World from Arial", position, Color.Red);
    
      spriteBatch.End();
    
  4. Run the program. Note how the text appears at the specified position.
  5. Change the font size in the Arial16.spritefont XML document, and run the program again.
  6. Change the font size back to 16.

Drawing at an Angle

Just as there are several versions of spriteBatch.Draw() offering options to scale and rotate a sprite, so there are similar variations of spriteBatch.DrawString() offering similar options. We'll explore how to draw text at an angle

The version of DrawString() which draws at an angle is this one:

  spriteBatch.DrawString(arial16, "Message", position, colour, rotation, 
                         origin, scale, spriteEffects.None, zPosition);

As with drawing normal sprites, the origin is the point about which the rotation will take place, and the position specifies where the the origin point will be placed on the display. The other parameters are as for normal sprites.

  1. Put the following field at the top of the Game1 class, just following the declaration of SpriteFont arial16:
      SpriteFont arial16;
      double rotation = 0.0;	// Define rotation in radians
    
  2. Add the following lines to Draw(), just before the call to spriteBatch.End():
      position = new Vector2(300, 300);  // Assumes position already declared
      Vector2 origin = new Vector2(60, 14);
      spriteBatch.DrawString(arial16, "Rotation", position, Color.Yellow, (float)rotation, 
          origin, 1.0f, SpriteEffects.None, 0.5f);
    
  3. Run the program. The new text should be written normally across the screen.
  4. Change the value of the rotation field - now the text should be written at an angle.
  5. Modify the Update() method so that the text slowly rotates on the screen.

Loading More Fonts

A serious limitation of sprite fonts is that each one has a fixed font size which you can't change whilst the program is running. This means that you need to create a different sprite font for every different type face and every different font size you use!

(Sure, the DrawString() method has a scale parameter, but this is only useful for making minor size adjustments - otherwise it just doesn't look right)

Let's load a second font; this time we'll use one with a mouthful of a name: Franklin Gothin Medium

  1. Put the mouse on the Content section of the solution explorer. Right click and select Add > Add New...
  2. Create a new sprite font with the name Franklin20.spritefont:
  3. Edit the Franklin20.spritefont file and change the font name to Franklin Gothic Medium (note spaces and capitals). Also change the font size to 20:

  4. Add a new field to the Game1 class:
      SpriteFont franklin20;
    
  5. Add a new statement to the LoadContent() method:
      franklin20 = this.Content.Load("Franklin20");
    
  6. Add some more DrawString() calls to the Draw() method to write a few more messages using the Franklin font.

Cross Purposes

In this section, we're going to show an interesting criss-cross effect using rotation. Look how the word "mouse" crosses over itself:

This is achieved by writing "mouse" horizontally, and then writing "m use" across it at right angles so both strings share the same letter "o". We set the origin point so that it is in the centre of the "o" for both of the DrawString() operations.

For this to work, we need to know that the angle 90° is the same as Pi/2 radians. The standard C# class Math has a a property which will give us the value of Pi: Math.PI

If we want to divide this by two, then we can just write: Math.PI/2.0

This value is a double, but DrawString() requires a float value for the rotation. This means we must cast the value into a float, like this: (float)(Math.PI/2.0)

  1. Remove or comment out all the statements you have previously put into the Draw() method, except for the spriteBatch.Begin and End calls.
  2. Put the following statements between the spriteBatch.Begin and End:
      Vector2 mousePosition = new Vector2(300, 400);
      Vector2 mouseOrigin = new Vector2(32, 19);
    
      spriteBatch.DrawString(franklin20, "mouse", mousePosition, Color.White, 0f,
          mouseOrigin, 1.0f, SpriteEffects.None, 0.5f);
    
      spriteBatch.DrawString(franklin20, "m  use", mousePosition, Color.White, (float)(Math.PI/2),
          mouseOrigin, 1.0f, SpriteEffects.None, 0.5f);
    
  3. Confirm that this writes the text as shown above.

On Your Own

Use what you've learned so far to modify the project so that:

  1. Both parts of the criss-cross mouse text slowly rotate about the origin point (centre of the letter "o").
  2. The criss-cross text tracks the current position of the mouse - while still rotating.

If you've been paying attention then both of these enhancements are very easy!


Tidying Up When You've Finished

When you've finished all the steps above, you need to close down Game Studio Express as follows:


Return to home page