Monogame - Drawing Text With Spritefonts

Overview

In many games, there are times where we want to draw text on the screen, along with other image sprites, or 3D stuff. MonoGame lets you draw text using the SpriteFont class, coupled with the SpriteBatch class that we saw in the previous tutorial. In this tutorial, we will make a game that draws some text on the screen. After that we will take a look at an intuitive extension to that idea: drawing the value of a variable, like a score, to the screen.

Acquiring Fonts

On a computer, fonts are generally defined mathematically, as opposed to being rendered as an image. This allows you to change the point size of text, and not have it become pixellated. This type of graphics is called vector graphics, because everything is defined in terms of vectors. However, this is bad for game programming. Since speed is almost always an issue, we want to be able to quickly draw our text, rather than having to spend vast amounts of computation cycles to determine what pixels should be lit up.

In MonoGame, we will work with a thing called sprite fonts. A sprite font takes a normal, vector-based font and turns it into a bitmapped font that can be drawn quickly. The content pipeline makes this very easy to do.

When you start selecting fonts to use, it is important to pay careful attention to copyrights and licensing. For many of the fonts that come with your computer, you may not have the rights to put it into a game and sell it commercially.

To guarantee that a particular font can be used in your game, you should confirm that the license for the font specifically allows this. If you can't find the proof that a font can be legally reused in a commercial game, then you should assume it can't, and move on to a different font. (Or find a way to contact the creator of the font and get permission. But again, a lack of a response does not automatically give you permission.)

Typically, the best way to find a font for your game is to find a font distribution website that includes copyright and licensing information. For example, http://www.dafont.com is one I've used quite a bit and liked. You can even filter to fonts that have commercial-use licenses for free.

There are plenty of other font websites out there, so if dafont.com doesn't have what you're looking for, keep looking around.

The other options you have are to go hunt down individual "font foundries" on the Internet and buy a license from them or make your own fonts. (If you have some art skills, this isn't so difficult to pull off, but does take time.)

For the sake of this tutorial, I'm just going to stick with Arial, since just about everybody has the font already installed on their computer.

Making a Sprite Font

The next step is to actually get a sprite font art asset added to our game. To do this, we first start by going to MonoGame's Pipeline Tool and add a new sprite font to it.

Like we've done with content before, the first step is to open MonoGame's Pipeline Tool, which can be done by:

1. Open up your game's Content folder and locate Content.mgcb.
2. Right-click and choose Open With…
3. Find MonoGame Pipeline Tool and select it.
4. Optionally, hit the Set as Default button if you want to be able to just double-click on the item in the future.
5. Hit OK to open the file.

This will open the MonoGame Pipeline Tool, shown below.

MonoGamePipelineTool.png

To add a sprite font, rather than adding an existing item, we will add a new item.

Right-click on the Content node in the tree on the left (or add a directory under it, where you want to place your new font).

MonoGamePipelineToolNewItem.png

This will open up the New Item dialog. (Note that there is a button in the toolbar that does this as well.)

In here, choose SpriteFont Description from the list, and give it a name at the bottom. I've called mine "Score". When you're done, hit the Ok button.

MonoGamePipelineToolNewItemDialog.png

Once you've done this, you'll see your sprite font now shows up in your content tree on the left side.

FontAdded.png

The Pipeline Tool doesn't have an obvious way of editing this file, but it is a simple XML file, which can be edited with your favorite text editor. (You can see in the picture that I've got Notepad++ set up as my default editor for that.)

You will have to edit the file if you want to change the font, the size, or any of a number of other properties that it contains. It's worth a peek in there to see what it has, so go ahead and open it up.

Down at about line 14 you will see the following:

<FontName>Arial</FontName>

This says the name of the font that we want to use. Arial is the default for MonoGame, primarily because it has a very permissive license and is found on virtually all platforms everywhere.

If you want to use a different font, just replace this name with the name of the font that you want to use. You can use any font that you have installed on your computer. (Fonts can be installed by dragging the font file to your Fonts folder, which is located in C:/Windows/Fonts, or something similar.)

Also look down at line 20, where it says:

<Size>12</Size>

This indicates the font size that we want. I want mine to be a bit bigger, so I'm going to change it to 24.

There are a couple of other values that we could change in this file as well, but I'll let you look at those on your own. The comments in the XML file are pretty descriptive.

It's important to point out that when you compile your project and the art assets are compiled, the content pipeline will produce an actual sprite font (ultimately, an image file) from the named font and its properties. This sprite font will be accessible in your game, but not the original font file. You'll be able to do a number of transformations on the font at run-time, including changing colors and scaling, but it is "rasterized" to pixels at compile time and you won't be able to change it easily.

There may be times where it will make sense to have multiple sprite fonts in your game for a single font family to account for different sizes, font faces, and character ranges.

Using the Sprite Font

Now that we've got a sprite font in our content, let's go ahead and use it. Go to the top of your class and add the following two variables as instance variables to the class:

private SpriteFont font;
private int score = 0;

This first variable will store our font for drawing. The second variable, score will give us a value to draw to the screen.

Now let's load the font by adding the following line of code to the LoadContent() method:

font = Content.Load<SpriteFont>("Score"); // Use the name of your sprite font file here instead of 'Score'.

Now let's actually use the sprite font to draw. Let's go down to the {{Draw()} method and add the following code:

spriteBatch.Begin();
 
spriteBatch.DrawString(font, "Score", new Vector2(100, 100), Color.Black);
 
spriteBatch.End();

If you already have a spriteBatch.Begin()spriteBatch.End() block (from a previous tutorial or something), you can just add the middle line to the body of it instead.

The only really new piece of information here is the middle line of code. We use the spriteBatch.DrawString method, which allows us to draw text. The first parameter that we have is the SpriteFont that we want to use. We're just going to use our font object. The next parameter is the text to display. We want to draw the word "Score", so that is what we put in. The third parameter is the location on the screen that we want the text drawn at. The fourth and final parameter is the color of the text. I've chosen to draw the text in black.

We can now run our program and see our text being drawn. It should look like the screen capture below:

FirstRun.png

This is a great first step, but let's also draw a the current score of our game. Remember that we defined a score variable earlier.

In the Update() function, let's let the score change, by adding the following line of code there:

score++;

Now let's replace our original spriteBatch.DrawString line with the following:

spriteBatch.DrawString(font, "Score: " + score, new Vector2(100, 100), Color.Black);

I've changed the text that is displayed to be the word 'Score: ' followed by whatever is in the score variable. Notice that I'm using the '+' operator on a string and an int. C# is smart enough to realize that in this instance, since the first part was a string, that it should take the int and convert it to a string before appending them together.

If we run this now, we will be able to see our actual score being displayed, like below.

SecondRun.png

What's Next?

We have now seen how we can draw text in our game, which has many applications. From here, we can go learn more about some advanced features of sprite drawing, like rotating sprites, texture atlases, or simple 2D particle engines. Each of these are discussed in other tutorials.


Troubleshooting.png Having problems with this tutorial? Try the troubleshooting page!