如何使由SpriteBatch.DrawString绘制文本?(How to align text

2019-07-29 02:48发布

有一种简单的方法来对齐文本的权利和中心(而不是默认的左)?

Answer 1:

第一步是测量使用串SpriteFont.MeasureString()

然后,例如,如果你想把它画到某个点的左边,而不是位于右侧是默认的,那么你就需要从文本绘制原点减去测量的X宽度。 如果你希望它为中心,那么你可以使用一半的测量等。



Answer 2:

我用这个代码:

 [Flags]
 public enum Alignment { Center=0, Left=1, Right=2, Top=4, Bottom = 8 }

 public void DrawString(SpriteFont font, string text, Rectangle bounds, Alignment align, Color color )
    {
        Vector2 size = font.MeasureString( text );
        Vector2 pos = bounds.GetCenter( );
        Vector2 origin = size*0.5f;

        if ( align.HasFlag( Alignment.Left ) )
            origin.X += bounds.Width/2 - size.X/2;

        if ( align.HasFlag( Alignment.Right ) )
            origin.X -= bounds.Width/2 - size.X/2;

        if ( align.HasFlag( Alignment.Top ) )
            origin.Y += bounds.Height/2 - size.Y/2;

        if ( align.HasFlag( Alignment.Bottom ) )
            origin.Y -= bounds.Height/2 - size.Y/2;

        DrawString( font, text, pos, color, 0, origin, 1, SpriteEffects.None, 0 );
    }


Answer 3:

SpriteFont mFont;
SpriteBatch mSprite;

mSprite.Begin();
mSprite.DrawString(mFont, "YourText", new Vector2(graphicsDevice.Viewport.Width / 2 - mFont.MeasureString("YourText").Length() / 2, 0), Color.White, 0, new Vector2(0, 0), 1f, SpriteEffects.None, 0f);
mSprite.End();


文章来源: How to align text drawn by SpriteBatch.DrawString?