65.9K
CodeProject 正在变化。 阅读更多。
Home

XNA 通知框

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.90/5 (3投票s)

2010年8月28日

CPOL

2分钟阅读

viewsIcon

13613

downloadIcon

356

一个可以在游戏中放置的通知框,用于向用户更新正在发生的事情(如许多射击游戏中所示)

引言

令人惊讶的是,在互联网上很难找到代码,让你能够轻松地显示一个通知框,在你想显示的位置、时间和大小。好吧,我现在已经创建了一个类,希望能解决所有这些问题。

Using the Code

这个类很简单,要使用它,你只需要修改一些小地方。这些是:

  1. FontLocation - 用于绘制文本的 spriteFont 的位置
  2. DisplayedText - 简单地使用 'DisplayedText = ' 来向框中添加一行文本

我的代码编写方式是,通知框会显示一段时间,然后逐渐淡出直到透明。当添加更多文本时,它会再次显示。代码会自动将文本分成多行,以防止溢出指定的矩形。当你使用 'DisplayedText = ' 时,我的代码会将它添加到当前文本的开头,将文本分成多行,然后显示它。代码中最难的部分是将文本分成多行,否则会有一段无休止的文本溢出通知框。我使用的代码部分来自 MSDN 网站,但为了获得更大的灵活性并实现我想要的功能,对其进行了修改。最终代码如下所示:

private string parseText(string SomeText)
{
	//Create a string to return that is empty
	String returnString = String.Empty;
	//Create a list of lines that are already in the text 
         //so that they remain separated
	String[] ExistingLines = SomeText.Split("\n".ToCharArray());
	//Create a list to contain the new lines of text.
	List<String> Lines = new List<String>();
	//For every existing line, check its length and split it up if it's too long.
	foreach (String ALine in ExistingLines)
	{
		//Current line that is being split up
		String line = String.Empty;
		//Lines that this existing line has been split up into
		List<String> CLines = new List<String>();
		//Words in this existing line
		String[] wordArray = ALine.Split(' ');
		//For each word, check if it will fit on the current line, 
		//if not create a new line and add the old one to the CLines object.
		foreach (String word in wordArray)
		{
			//Check to see if word will fit on current line.
			if (TheFont.MeasureString(line + word + " ").Length() > 
							SurroundingBox.Width)
			{
				//If not, add the line to CLines with a new line 
				character on the end to make sure that the text is 
				split when it is drawn.
				CLines.Add(line + "\n");
				//Reset the current line to blank.
				line = String.Empty;
			}
			//Add the word to the current line.
			line = line + word + ' ';
		}
		//Add the current line to Clines as it won't already have been added.
		CLines.Add(line + "\n");
		//For every line this existing line has been split up into, 
						add it to the final set of lines.
		foreach (string TheLine in CLines)
		{
			Lines.Add(TheLine);
		}
	}
	//Remove the first line until the number of lines is less than the maximum.
	while(Lines.Count > MaxLines)
	{
		Lines.RemoveAt(0);
	}
	//Add the final set of lines to the return string.
	for (int i = 0; i < Lines.Count; i++)
	{
		returnString += Lines[i];
	}
	return returnString;
}

如你所见,它会查看传递给它的文本,将其分成现有的行,然后查看这些行是否有太长的。如果有,代码会将它们分成多行,并用新行替换原始行。最后,它将所有这些行连接成一个 string 并返回该 string

就这样了!除了在相关点调用 draw、update 和 resize 函数外,你只需要给框提供一些要显示的文本!

关注点

我发现这既有趣又令人恼火,虽然 spriteBatch.DrawString 函数识别转义字符 \n 并绘制新行,但没有提供用于在框内绘制 string 的函数。

历史

  • 2010 年 8 月 28:初始发布
© . All rights reserved.