Draw Horizontally Centered Text in XNA
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).
This article has been view 5278 times.
|