Text Rendering in Windows Phone Game


In this article I will show how to create sprite fonts in a Windows Phone game.

Open Visual Studio -> Create new project.

From the templates select "XNA Game Studio 4.0". From the project types select "Windows Phone Game 4.0".
Name your project.

Right click the content project and add new item.

WindowsPhone1.gif

Select Sprite Font and name it something meaningful.

When we are done with it, we are provided with a XML file with details of the sprite font like fontname, size, style etc. We can customize the appearance of the font in your game.

Now since the changes have been done, we are now ready to use the sprite fonts in our game.

Define

SpriteFont myFont;
Vector2 position;

Change the LoadContent method of your game class in the following way:

protected override void LoadContent()
{
    // Create a new SpriteBatch, which can be used to draw textures.
    spriteBatch = new SpriteBatch(GraphicsDevice);
    myFont = Content.Load<SpriteFont>("myFont");
    // TODO: use this.Content to load your game content here
}

Change the Update method of your game class to get the mouse position to draw the sprite font.

protected override void Update(GameTime gameTime)
{
    // Allows the game to exit
    if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
        this.Exit();

    // get the "mouse" position here
    var mouseState = Mouse.GetState();

    if (mouseState.LeftButton == ButtonState.Pressed)
    {
        position = new Vector2(mouseState.X,mouseState.Y);
    }
    base.Update(gameTime);
}

Once we have the loaded the sprite font and position, we draw it with the Draw method.

protected override void Draw(GameTime gameTime)
{
    GraphicsDevice.Clear(Color.Black);

    // TODO: Add your drawing code here
    spriteBatch.Begin();

    spriteBatch.DrawString(myFont, "Praveen Kumar", position, Color.Wheat);
    spriteBatch.End();
    base.Draw(gameTime);
}

Up Next
    Ebook Download
    View all
    Learn
    View all