use*_*322 13 c# xna text drawstring alignment
有没有一种简单的方法可以将文本对齐到右边和中心(而不是默认左边)?
Bla*_*lau 17
我用这个代码:
[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 );
}
Run Code Online (Sandbox Code Playgroud)
Ken*_*rey 16
第一步是使用测量字符串SpriteFont.MeasureString().
然后,例如,如果要将其绘制到某个点的左侧而不是默认的右侧,则需要从文本绘图原点中减去测量的X宽度.如果您希望它居中,那么您可以使用一半的测量值等.