c# XNA -遍历项并绘制它们

本文关键字:绘制 XNA 遍历 | 更新日期: 2023-09-27 18:11:29

下面是我的代码:

// Variables
private SpriteFont font;
private Vector2 fontPos, fontOrigin;
private List<string> menuItems;
// LoadContent()
font = Content.Load<SpriteFont>("myFont");
fontPos = new Vector2(1920 / 2, 1080 / 2);
menuItems = new List<string>();
menuItems.Add("Single Player");
menuItems.Add("Multi Player");
menuItems.Add("Achievements");
menuItems.Add("Options");
menuItems.Add("Quit Game");
// Draw()
for (int i = 0; i < menuItems.Count; i++)
{
    Vector2 fontOrigin = Game.gameFontLarge.MeasureString(menuItems[i]) / 2;
    spriteBatch.DrawString(Game.gameFontLarge, menuItems[i], new Vector2(ScreenManager.Instance.Dimensions.X / 2, ScreenManager.Instance.Dimensions.Y / 2), Game.NoTint, 0.0f, fontOrigin, 1.0f, SpriteEffects.None, 0.0f);
}
到目前为止,这段代码绘制了所有内容,但所有文本都是在相同的坐标(屏幕中心)上相互绘制的。如何使列表中的每个字符串都位于前一个字符串的下方,就像24像素低于前一个一样?

c# XNA -遍历项并绘制它们

如果我正确地阅读了您的问题,当您绘制字符串时,您可以简单地根据其索引为每个字符串的y值添加固定像素量。

所以这一行:

spriteBatch.DrawString( . . . , new Vector2(ScreenManager.Instance.Dimensions.X / 2, ScreenManager.Instance.Dimensions.Y / 2), . . .);

变得像下面这样:

spriteBatch.DrawString( . . . , new Vector2(ScreenManager.Instance.Dimensions.X / 2, (ScreenManager.Instance.Dimensions.Y / 2) + 24 * i), . . .);

希望这个解决方案为您工作-我不完全熟悉XNA,但这应该是一般的想法。如果它给你一个类型不匹配的错误,你可能需要用(float)i来转换i