Introduction
It is surprisingly difficult to find code on the internet that will let you easily display a notification box where, when and what size you want. Well, I've now produced a class that will (hopefully) solve all these problems.
Using the Code
The class is simple and to use it, you need only change a few small things. These are:
FontLocation
- The location of the spriteFont used to draw the text
DisplayedText
- Simply do 'DisplayedText =
' to add a line of text to the box
My code is written so that the notification box is displayed for a set length of time, then fades out till it is transparent. It is displayed again when more text is added. The code automatically splits the text into lines so none spills over the edge of the specified rectangle. When you do 'DisplayedText =
', my code adds it to the start of the current text, splits the text into lines, then displays it. The hardest bit of the code was splitting the text up into lines as otherwise there would be one endless string of text that spilled outside the notification box. The code I used was in part from the MSDN website but modified to allow for more flexibility and so it did what I actually wanted. The final code looks like this:
private string parseText(string SomeText)
{
String returnString = String.Empty;
String[] ExistingLines = SomeText.Split("\n".ToCharArray());
List<String> Lines = new List<String>();
foreach (String ALine in ExistingLines)
{
String line = String.Empty;
List<String> CLines = new List<String>();
String[] wordArray = ALine.Split(' ');
foreach (String word in wordArray)
{
if (TheFont.MeasureString(line + word + " ").Length() >
SurroundingBox.Width)
{
character on the end to make sure that the text is
split when it is drawn.
CLines.Add(line + "\n");
line = String.Empty;
}
line = line + word + ' ';
}
CLines.Add(line + "\n");
add it to the final set of lines.
foreach (string TheLine in CLines)
{
Lines.Add(TheLine);
}
}
while(Lines.Count > MaxLines)
{
Lines.RemoveAt(0);
}
for (int i = 0; i < Lines.Count; i++)
{
returnString += Lines[i];
}
return returnString;
}
As you can see, it looks at the text it has been passed, splits it up into existing lines, then looks at those to see if any are too long. If they are, the code splits them up and re-adds the new lines in place of the original line. Finally, it concatenates all those lines into one string
and returns that string
.
And that's it! Apart from calling the draw, update and resize functions at the relevant points, all you need to do is give the box some text to display!
Points of Interest
I found it both interesting and annoying that although the spriteBatch.DrawString
function recognises the escape character \n
and draws a new line, no function for drawing a string
inside a box is provided.
History
- 28th August, 2010: Initial post