XNA has Spritefont class, which has a MeasureString method, which can return the Width and Height of a string
. I\'m trying to understand how to create a method
To handle a block of text with carriage returns you need to modify the code as below:
public static string WrapText(SpriteFont font, string text, float maxLineWidth)
{
string[] words = text.Split(' ');
StringBuilder sb = new StringBuilder();
float lineWidth = 0f;
float spaceWidth = font.MeasureString(" ").X;
foreach (string word in words)
{
Vector2 size = font.MeasureString(word);
if (word.Contains("\r"))
{
lineWidth = 0f;
sb.Append("\r \r" );
}
if (lineWidth + size.X < maxLineWidth )
{
sb.Append(word + " ");
lineWidth += size.X + spaceWidth;
}
else
{
if (size.X > maxLineWidth )
{
if (sb.ToString() == " ")
{
sb.Append(WrapText(font, word.Insert(word.Length / 2, " ") + " ", maxLineWidth));
}
else
{
sb.Append("\n" + WrapText(font, word.Insert(word.Length / 2, " ") + " ", maxLineWidth));
}
}
else
{
sb.Append("\n" + word + " ");
lineWidth = size.X + spaceWidth;
}
}
}
return sb.ToString();
}