Home | Upgrading to XNA 2.0| Forum



 

XNA Fonts - for XNA 2.0

The XNA Refresh was the first framework to include XNA fonts. What makes them so attractive is they are easy to implement. Plus XNA fonts offer you a wide variety of styles and sizes which can handle most of your needs. With the timing of the release for the Microsoft XNA Game Studio Creator's Guide we couldn't manage to discuss them in the book so I'm explaining how to use them here.

This demonstration shows how to add XNA fonts to your game project. When you finish, the fonts will appear in your window to show your name, display your scores, or to tell you about any other important statistics like your shield strength or health level. The output from the demonstration looks similar to this (I increased the size of the font for this screen shot).

This example begins with the starter files that begin with the book. You can also download them from here. To add a reference to the font type, in Solution Explorer the font can be added by right clicking the Content node, choosing Add and select New Item .

In the Add New Item dialog that appears, choose the SpriteFont icon to select the template that automatically generates the spritefont file. You are required to enter a name for this file. For the purposes of this demonstration, type in ArialMedium . spritefont .

Once you click Add , this will generate an XML file called Arial.spritefont which is then automatically placed in your project. At this point you will see the spritefont file referenced in Solution Explorer .

If you view the contents of the spritefont file you will see code similar to the following:

<? xml version = " 1.0 " encoding = " utf-8 " ?>
<!--
This file contains an xml description of a font, and will be read by the XNA
Framework Content Pipeline. Follow the comments to customize the appearance
of the font in your game, and to change the characters which are available to draw
with.
-->
< XnaContent xmlns:Graphics = " Microsoft.Xna.Framework.Content.Pipeline.Graphics " >
< Asset Type = " Graphics:FontDescription " >
     
    <!--
    Modify this string to change the font that will be imported.
    -->
    < FontName > ArialMedium </ FontName >
     
    <!--
    Size is a float value, measured in points. Modify this value to change
    the size of the font.
    -->
    < Size > 14 </ Size >
     
    <!--
    Spacing is a float value, measured in pixels. Modify this value to change
    the amount of spacing in between characters.
    -->
    < Spacing > 2 </ Spacing >
     
    <!--
    Style controls the style of the font. Valid entries are "Regular", "Bold", "Italic",
    and "Bold, Italic", and are case sensitive.
    -->
    < Style > Regular </ Style >
     
    <!--
    CharacterRegions control what letters are available in the font. Every
    character from Start to End will be built and made available for drawing. The
    default range is from 32, (ASCII space), to 126, ('~'), covering the basic Latin
    character set. The characters are ordered according to the Unicode standard.
    See the documentation for more information.
    -->
     < CharacterRegions >
         < CharacterRegion >
            < Start > &#32; </ Start >
            < End > &#126; </ End >
        </ CharacterRegion >
    </ CharacterRegions >
</ Asset >
</ XnaContent >

You will need to adjust the <FontName> element in this file to reference a true type font on your system. To find a suitable name that can be used, you can view a listing of the true type fonts on your PC at C:\WINDOWS\Fonts .

To replace the FontName value with a reference to a true type font that actually exists, replace < FontName > ArialMedium </ FontName > with:


< FontName > Arial </ FontName >

Note that you can adjust the elements contained in the spritefont file to change the size of the font, spacing between characters, and you can also set the font to be Regular , Bold , or Italic in the <Style> element. For now, aside from changing the FontName , you can leave the default settings as is for this demonstration.

Fonts are drawn using both a SpriteBatch object and a SpriteFont object. If you are using the starter files for the Microsoft XNA Game Studio Creator's Guide, these declarations should be placed at the top of the Game1 class located inside Game1.cs .


SpriteBatch fontSpriteBatch;
SpriteFont  fontBatchArial;

Inside the Initialize() method, the content pipeline is used to initialize the fontBatch object with the XML file that was just added. As with all content pipeline loading, the file extension is not included when listing the name of the file to be read. Also, the SpriteBatch object that is used to draw the font must be initialized when the program begins.


fontBatchArial   = content.Load< SpriteFont >( "ArialMedium" );
fontSpriteBatch  = new SpriteBatch (gfx.GraphicsDevice);

The font is rendered from the Draw() method. It is drawn using an overridden DrawString() method. The parameters include the FontBatch object, output string, font position in the window, and color:

DrawString(FontBatch fontBatch, String output, Vector2 position, Color color);

When drawing with a SpriteBatch object, the process must start with the Begin() method and finish with the End() method.

When you add the code in, be sure to place it after all other objects are drawn. Drawing fonts last will prevent your text from being covered by other 3D objects that are inside the game world. In the end your 2D font will appear on the surface of your game window at all times.

Here is the code to add to the Draw() method to make this happen:


fontSpriteBatch.Begin();

// declare and initialize output string
string str = "XNA Fonts" ;

// starting x and y pixel on screen
Vector2 v2Pos = new Vector2 (50.0f, 50.0f);

// draw the output as text
fontSpriteBatch.DrawString(fontBatchArial, str, v2Pos, Color .Yellow);

fontSpriteBatch.End();

One last important item to note - when drawing 2D objects with a SpriteBatch it automatically adjusts the GraphicsDevice object to render in 2D. This makes drawing with SpriteBatch objects easy but the problem is many of the original GraphicsDevice settings are not restored. This may cause your 3D objects to disappear or it may cause your tiled images to be thrown out of whack. To restore the settings manually, after the fontSpriteBatch.End() statement add the following code:

 
gfx.GraphicsDevice.RenderState.CullMode          = CullMode .None; //see both sides
gfx.GraphicsDevice.RenderState.DepthBufferEnable = true;           //re-enable 3D on Z
gfx.GraphicsDevice.RenderState.AlphaBlendEnable  = false;          //disable transparent
gfx.GraphicsDevice.RenderState.AlphaTestEnable   = false;          //per pixel testing

// re-enable tiling
gfx.GraphicsDevice.SamplerStates[0].AddressU     = TextureAddressMode .Wrap;
gfx.GraphicsDevice.SamplerStates[0].AddressV     = TextureAddressMode .Wrap;


When you run your project now, the window should appear with your text on it. The solution can be downloaded from here.

- Pat McGee