Fun Infused Games  |   Smooth Operator

  Home   |    Archive   |    About
Posts prior to 8/2/2010 may be missing data. If you need one of those posts, please contact and I will try and recover/find it.

Draw Horizontally Centered Text in XNA
Date 3/28/2009    Tags XNA    (0)

Because there is no built in function for centering text drawn to the screen in XNA, I have created a small static method that will take in a string and draw it centered horizontally on the screen.

You will need to pass this method a few parameters so that it can figure out how to center the text and then draw your text (this is why you must pass it spriteBatch for instance). I've also allowed you to specify the color to draw your text and its vertical position.

/// <summary>
/// Take a string and draw it centered horizontally on the screen.
/// </summary>
public static void DrawCentered(String myText, int ScreenWidth, int yPosition, Color drawColor, SpriteFont spriteFont, SpriteBatch spriteBatch)
    // Get the size the spritefont will be drawn on the screen.

    Vector2 textSize = spriteFont.MeasureString(myText);

    // Get the position we need to draw the text at for it to be centered.
    int centerXPosition = (ScreenWidth / 2) - ((int)textSize.X / 2);

    // Draw the centered text.
    spriteBatch.DrawString(spriteFont, myText, new Vector2(centerXPosition, yPosition), drawColor);
It wouldn't be hard to modify this if you wanted to draw text centered horizontally too or to add an effect like a drop-shadow (draw black text slightly offset from the normal text).

kick it on

This article has been view 5278 times.


No comments for this article.

Add Comments

Name *
  Name the animal in the picture below:

Comment *
Insert Cancel
Things To Click

Video Games (7)  Trivia or Die (3)  SQL (1)  iOS (3)  Game Dev (11)  Advise (14)  PC (1)  World of Chalk (2)  FIN (20)  Abduction Action! (27)  XBLIG (32)  Abduction Action (1)  Nastier (4) (18)  Absurd (2)  Volchaos (11)  Web (19)  Fin (1)  XNA (40)  Rant (50)  Cool (2)  Visual Studio (1)  Trivia Or Die (1)  Xbox (1)  C# (14)  Sports (11)  Design (2)  Development (13)  Hypership (28)  WP7 (8)  VolChaos (1)  Nasty (34)  Abdction Action! (1)