如何使用spritebatch绘制字符串列表,使其看起来像这样;
Item1 Item2
Item3 Item4
而不是第1项第2项第3项第4项或代替:
Item1
Item2
Item3
Item4
答案 0 :(得分:2)
这样的事情会让以后更容易改变:
int y = startPointY;
int x = startPointX;
int switchAt = items.Count/2; //<--- or where ever you might want to break up the strings
int max = 0;
for(int i = 0; i < items.Count; i++)
{
spriteBatch.DrawString(font, items[i], new Vector2(x, y), Color);
if(max < spriteFont.MeasureString(items[i]))
{
//this is to make sure the next column of strings are aligned
max = spriteFont.MeasureString(items[i]);
}
y += someYSpace;
if(i == switchAt)
{
x += max + someXSpace;//someXSpace not neccessary
y = startPointY;
}
}
现在,您可以猜测大致位置以使字符串居中....或者,您可以找到并排的字符串的长度,测量它们之间的总空间量,以及其他一些棘手的东西要弄清楚哪些字符串应放在哪里......换句话说,让它们完全居中将是一种痛苦,可能比它的价值更麻烦,据我所知。
您重构的代码:
Color color;
int linePadding = 3;
int switchAt = buttonList.Count / 2 - 1;//minus one because the list starts at 0, and goes up to 3, so 1 is the switch point
else
{
spriteBatch.Draw(mMenuPhoto, new Rectangle(800, 150, mMenuPhoto.Width, mMenuPhoto.Height), Color.White);
float X = 210;
float Y = 600 - (spriteFont.LineSpacing * (buttonList.Count) / 2) + ((spriteFont.LineSpacing + linePadding));
float max = 0;
float linesXSpace = 30;//to seperate this lines to make room for '|'
for (int i = 0; i < buttonList.Count; i++)
{
color = (i == selected) ? Color.LightGray : Color.DarkSlateGray;
if (max < spriteFont.MeasureString(buttonList[i]).X)
{
max = spriteFont.MeasureString(buttonList[i]).X;
}
if (i != selected)
{
spriteBatch.DrawString(spriteFont, buttonList[i], new Vector2(X, Y), color);
Y += spriteFont.MeasureString(buttonList[i]).Y;
if (i == switchAt)
{
X += max + linesXSpace;
Y = 600 - (spriteFont.LineSpacing * (buttonList.Count) / 2) + ((spriteFont.LineSpacing + linePadding));
}
}
else
{
spriteBatch.DrawString(spriteFont, buttonList[i], new Vector2(X, Y), color);
spriteBatch.DrawString(spriteFont2, "|", new Vector2(X - 20, Y), Color.DarkGreen);
Y += spriteFont.MeasureString(buttonList[i]).Y;
if (i == switchAt)
{
X += max + linesXSpace;
Y = 600 - (spriteFont.LineSpacing * (buttonList.Count) / 2) + ((spriteFont.LineSpacing + linePadding) * i);
}
}
}
}
P.S。我喜欢它到目前为止的样子^^。