Page 1 of 1

How to Draw : Text in XNA A tutorial for displaying text in XNA

#1 Hellbroth  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 17
  • View blog
  • Posts: 190
  • Joined: 15-August 09

Posted 17 January 2010 - 11:38 PM

Start a new XNA Project and at the right click on the Content and select add New Item and then select
Sprite Font.You can name it as you want for this tutorial i left the name as it was.

So now that we have everything we need let's start writting some code. I will right first the code and i will explain it after.

After the spriteBatch we will create a SpriteFont it's the same way as when you create a Texture2D.


SpriteFont spriteFont;
Vector2 spriteFontPosition = new Vector2(200,200);
string [] text = { "Hello World" };



So now we declared a SpriteFont then we assigned a position for the text that will be shown on the screen
and in the end we create a string named text to put inside the text that we want to be shown on the screen.

Now we will go at the LoadContent method to load our spriteFont.

protected override void LoadContent()
		{
			// Create a new SpriteBatch, which can be used to draw textures.
			spriteBatch = new SpriteBatch(GraphicsDevice);

			spriteFont = Content.Load<SpriteFont>("SpriteFont1");
		}



What we did now is that we load our spriteFont from our Content so it can be used.
Finaly we will go at our draw method.

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

			spriteBatch.Begin();
			spriteBatch.DrawString(spriteFont, text[0],spriteFontPosition,Color.Black);
			spriteBatch.End();

			base.Draw(gameTime);
		}




We start our spriteBatch with the Begin.Then we our using the DrawString method, first is the name of our declared spriteFont, then we put our string and i gave the value 0 there cause there is only one thing in our string and is the first thing(Never forget that in a string the position starts from 0 and not 1) then we give our spriteFontPosition Vector2 for the spriteFont position and in the end our Color.

Congratulations this is your first text in XNA.


One last tip if you want to display numbers then you simple have to create an integer to store the value for example :

 int value = 1;


and after that go at the Draw method in the DrawString and add this :

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


			spriteBatch.Begin();
			spriteBatch.DrawString(spriteFont, text[0]+value.ToString(),spriteFontPosition,Color.Black);
			spriteBatch.End();

			base.Draw(gameTime);
		}



What i did was after the text[0] i put the + sign the name of my variable and then .ToString() so it can be converted from integer to string otherwise you would get an error.

That's all guys :)

Is This A Good Question/Topic? 0
  • +

Page 1 of 1