How to Display Text in your XNA Windows Phone 7 game

First thing you need to do is add a SpriteFont object to your code.

Done like this: SpriteFont myFont (or whatever name you want to give it).

SpriteFont mySpriteFont

Add SpriteFont

Next you need an actual font you can load. For that you go to your solution explorer and right click your content project. Select add -> new item -> SpriteFont.

Add new item

Add SpriteFont to content project

Maybe you should select a better name, that the default one. But it doesn’t really matter much.

Select SpriteFont

Add SpriteFont

You can edit how your font looks like in the .spritefont file. It is a XML like format. Most stuff you find in there should be pretty much self-explanatory. At the bottom you find tags specifying a character region. Please note, that not all fonts can display all characters. If you happen onto a bug resulting from some character display problem or exception, have a look here, if your font can display all your characters. The rest describes size, text decoration and stuff.

spritefont file

The font description

For this post, I leave everything like it is and go on to actually displaying something on the phone.

First we need to load our SpriteFont1 in the ContentLoad()-method of our game class.

myFont = Content.Load("SpriteFont1")

All we have to do is display some text now.

We go to the Draw-method and beginn the spriteBatch draw with SpriteBatch.Begin().  The spriteBatch-Class offers us a DrawString-mehtod we use to display text. It first parameter is our SpriteFont. The secont the String you wish to display. This could of course come out of some Sting variable. The third is the position of the text on the screen and the last one, the color in the text is drawn in. We complete this with a spriteBatch.End() in the next line.

And see the result here: I made the Font bigger and red for this example. The size is controlled in the .spritefont file, the color can be selected in the DrawString-method.

Text on WP7 emulator

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: