XNA - Drawing Strings on Menus

2019-09-08 05:02发布

问题:

Two questions on Drawing a list of Strings on XNA in menus. First is how do you left align the text instead of center align it? Second is how do you show a say a line before whichever one is selected? Here is the code I have for it so far;

    public void Draw(SpriteBatch spriteBatch, GameTime gameTime)
    {
        Color color;
        int linePadding = 3;

        if (gameTime.TotalGameTime.TotalSeconds <= 3)
        {
            spriteBatch.Draw(mTheQuantumBros2, new Rectangle(300, 150, mTheQuantumBros2.Width, mTheQuantumBros2.Height), Color.White);
        }
        else
        {
            for (int i = 0; i < buttonList.Count; i++)
            {
                color = (i == selected) ? Color.Gold : Color.LawnGreen;
                spriteBatch.DrawString(spriteFont, buttonList[i], new Vector2((screenWidth / 2) - (spriteFont.MeasureString(buttonList[i]).X / 2), (screenHeight / 2) - (spriteFont.LineSpacing * (buttonList.Count) / 2) + ((spriteFont.LineSpacing + linePadding) * i)), color);
            }
        }
    }

回答1:

Hmm.. honestly I think center aligning would look better, but in your code all you would need to do is change draw string to this:

for (int i = 0; i < buttonList.Count; i++)
{
     color = (i == selected) ? Color.LawnGreen : Color.Gold;
     spriteBatch.DrawString(spriteFont, buttonList[i], new Vector2((screenWidth / 2) /*- (spriteFont.MeasureString(buttonList[i]).X / 2)*/, (screenHeight / 2) - (spriteFont.LineSpacing * (buttonList.Count) / 2) + ((spriteFont.LineSpacing + linePadding) * i)), color);
}

You can see what I commented out. By taking that out, you are no longer moving the string to the left by half of its width.

As for the second part, all you need to do is check if the value is selected, as you are already doing to determine the menu item color. If it is selected, simply add "|" to the front and end of the string:

for (int i = 0; i < buttonList.Count; i++)
{
     color = (i == selected) ? Color.LawnGreen : Color.Gold;
     if(i != selected)
     {
         spriteBatch.DrawString(spriteFont, buttonList[i], new Vector2((screenWidth / 2) /*- (spriteFont.MeasureString(buttonList[i]).X / 2)*/, (screenHeight / 2) - (spriteFont.LineSpacing * (buttonList.Count) / 2) + ((spriteFont.LineSpacing + linePadding) * i)), color);
     }
     else
     {
         spriteBatch.DrawString(spriteFont,"|" + buttonList[i] + "|", new Vector2((screenWidth / 2) - (int)spriteFont.MeasureString("|").X, (screenHeight / 2) - (spriteFont.LineSpacing * (buttonList.Count) / 2) + ((spriteFont.LineSpacing + linePadding) * i)), color);
     }
}

Now, since you are adding the "|" to the beginning of the string, that will effect the position. By subtracting the measured width of "|", the string is then recentered.



标签: c# menu xna