How to align text drawn by SpriteBatch.DrawString?

我是研究僧i 提交于 2019-12-04 10:37:03

问题


Is there an easy way to align text to the right and center (instead of default left)?


回答1:


The first step is to measure the string using SpriteFont.MeasureString().

Then, for example if you want to draw it to the left of a certain point, instead of to the right as is the default, then you need to subtract the X width of the measurement from the text drawing origin. If you want it to be centered, then you can use half the measurement, etc.




回答2:


I use this code:

 [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 );
    }



回答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();


来源:https://stackoverflow.com/questions/10263734/how-to-align-text-drawn-by-spritebatch-drawstring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!