0

我正在尝试在单机游戏窗口中做一个应用程序。我有一个长文本要显示在屏幕上。我尝试使用 spriteBatch.Drawstring 在屏幕上渲染它,在一定程度上是成功的。但是,文本不适合所需区域。我已按照教程进行操作。我需要一个垂直滚动来实现我想要的区域内的整个文本。任何人都可以提出一些帮助。这是我当前的代码:

protected override void LoadContent()
    {
        spriteBatch = new SpriteBatch(GraphicsDevice);
        _boxTexture = new SolidColorTexture(GraphicsDevice, Color.Red);
        _borderRectangle = new Rectangle(100, 100, 500, 500);
        _textboxRectangle = new Rectangle(105, 105, 490, 490);
        _font = Content.Load<SpriteFont>("Rockwell");
        _text = "He determined to drop his litigation with the monastry, and relinguish his claims to the wood-cuting and fishery rihgts at once. He was the more ready to do this becuase the rights had becom much less valuable, and he had indeed the vaguest idea where the wood and river in quedtion were.";

    }
private String parseText(String text)
{
String line = String.Empty;
String returnString = String.Empty;
String[] wordArray = text.Split(' ');

foreach (String word in wordArray)
{
    if (font.MeasureString(line + word).Length() > textBox.Width)
    {
        returnString = returnString + line + '\n';
        line = String.Empty;
    }

    line = line + word + ' ';
}

return returnString + line;
}

和内部绘图功能:

spriteBatch.DrawString(font, parseText(text), new Vector2(textBox.X, textBox.Y), Color.White);
4

1 回答 1

0

您可以改为在 draw 方法中执行此操作。然后就做你现在正在做的事情,但不是创建一个你返回的字符串,你只需调用

spriteBatch.DrawString(font, line, textPostion, Color.White);

反而。其中 textPosition 刚好等于文本框位置,首先是每次迭代都使用 font.MeasureString(line).Y 增加 Y 位置:

textPosition.Y += font.MeasureString(line).Y; 

然后你检查

if(font.MeasureString(line).Y + textPosition.Y < textBox.Y + textBox.Height 
   || textPosition.Y > textBox.Y)    
{
     continue;
}

然后只需查找键盘箭头的输入(或创建一些用于向上和向下滚动的按钮),并相应地增加或减少 textPosition.Y。然后你将有垂直滚动的文本框。

然后,您可以通过定义该位置的最小 Y 值来进行锁定,以便文本在滚动到底部或顶部时停止。

于 2015-07-09T14:16:18.563 回答