Fun Infused Games  |   Smooth Operator RSS 

  Home   |    Archive   |    Subscribe   |    Search   |    About
Posts prior to 8/2/2010 may be missing data. If you need one of those posts, please contact kriswd40@yahoo.com 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 GameDevKicks.com



This article has been view 5278 times.


Comments

No comments for this article.


Add Comments

Name *
Website
  Name the animal in the picture below:

*  
Comment *
Insert Cancel


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