0
\$\begingroup\$

I'm using SpriteBatch.DrawString, which seems to not have an overload for text alignment. How can I draw aligned text?

\$\endgroup\$
5
  • 1
    \$\begingroup\$ You should mention what framework you're using. \$\endgroup\$ Apr 8, 2014 at 18:48
  • \$\begingroup\$ It's probably XNA. \$\endgroup\$
    – Grey
    Apr 8, 2014 at 18:50
  • 1
    \$\begingroup\$ @Grey XNA and MonoGame typically are what would have a DrawString method like that, but you never know. :( \$\endgroup\$ Apr 8, 2014 at 18:51
  • 1
    \$\begingroup\$ If you're using XNA, there's already a really good extension method written over here: stackoverflow.com/questions/10263734/… \$\endgroup\$ Apr 8, 2014 at 18:52
  • \$\begingroup\$ yes thnx, thats what i was looking for \$\endgroup\$ Apr 8, 2014 at 19:38

1 Answer 1

1
\$\begingroup\$

I created a helper class in Ruminate MonoGame GUI that takes in the following arguments and lets you align or center the text within a Rectangle both vertically and horizontally. Passing in neither enum results in the same behavior as the default SpriteBatch function.

The options for the emuns are.

public enum TextHorizontal { LeftAligned, CenterAligned, RightAligned }
public enum TextVertical { TopAligned, CenterAligned, BottomAligned }

And the math in the function of interest is quite simple.

    public void Render(SpriteBatch spriteBatch, string value, Rectangle renderArea,
        TextHorizontal h = TextHorizontal.LeftAligned, TextVertical v = TextVertical.TopAligned) {

        var location = new Vector2(renderArea.X, renderArea.Y);

        var size = SpriteFont.MeasureString(value);

        switch (h) {
            case TextHorizontal.CenterAligned:
                location.X += (renderArea.Width - size.X) / 1.9f;
                break;
            case TextHorizontal.RightAligned:
                location.X += renderArea.Width - size.X;
                break;
        }

        switch (v) {
            case TextVertical.CenterAligned:
                location.Y += (renderArea.Height - size.Y) / 1.9f;
                break;
            case TextVertical.BottomAligned:
                location.Y += renderArea.Height - size.Y;
                break;
        }

        spriteBatch.DrawString(SpriteFont, value, location, Color);
    }
\$\endgroup\$
2
  • \$\begingroup\$ what is that magic / 1.9? \$\endgroup\$
    – API-Beast
    Apr 8, 2014 at 21:55
  • \$\begingroup\$ i think it shoudl be 2... maybe he uses 1.9 for some minor offset? \$\endgroup\$ Apr 9, 2014 at 13:07

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .