28Feb/11Off
Originally Posted 2009
OK I was doing my usual potter around the net tonight when I found "Draw Horizontally Centered Text in XNA" and thought I have to tweak this...
/// /// Take a string and draw it centered horizontally on the screen. /// 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); }
I hate passing parameters i don't need and you should strive to avoid magic numbers so I moved theĀ int ScreenWidth to be a local variable and pulled the required value in from theĀ SpriteBatch with the following line :-
// pick up the screen width. int ScreenWidth = spriteBatch.GraphicsDevice.Viewport.Width;
And as a sort of old school codey kick removed the division from the int centerXPosition calculation and replaced it with some bit shifts to bring us to
// Get the position we need to draw the text at for it to be centered. int centerXPosition = (ScreenWidth >> 1) - ((int)textSize.X >> 1);
so in all my replacement method is :-
/// /// Take a string and draw it centered horizontally on the screen. /// public static void DrawCentered(String myText, int yPosition, Color drawColor, SpriteFont spriteFont, SpriteBatch spriteBatch) { // pick up the screen width. int ScreenWidth = spriteBatch.GraphicsDevice.Viewport.Width; // 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 >> 1) - ((int)textSize.X >> 1); // Draw the centered text. spriteBatch.DrawString(spriteFont, myText, new Vector2(centerXPosition, yPosition), drawColor); }
Have fun with that, and thanks to Kris Steele for the original article






