XNA 有 Spritefont 类,该类有一个 MeasureString 方法,可以返回
string
的宽度和高度。我试图了解如何创建一个方法,该方法将有效地返回一个字符串,并将 Environment.Newline
插入到正确的位置,以便适合特定的宽度和高度(矩形用作其参数)。
我发现以下代码:XNA - 基本自动换行
public string WrapText(SpriteFont spriteFont, string text, float maxLineWidth)
{
string[] words = text.Split(' ');
StringBuilder sb = new StringBuilder();
float lineWidth = 0f;
float spaceWidth = spriteFont.MeasureString(" ").X;
foreach (string word in words)
{
Vector2 size = spriteFont.MeasureString(word);
if (lineWidth + size.X < maxLineWidth)
{
sb.Append(word + " ");
lineWidth += size.X + spaceWidth;
}
else
{
sb.Append("\n" + word + " ");
lineWidth = size.X + spaceWidth;
}
}
return sb.ToString();
}
为了添加 Alina 的答案,这里是该函数的扩展版本,它也会对长度超过 maxLineWidth 的单个单词进行换行
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 (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();
}
要处理带回车的文本块,您需要修改代码如下:
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();
}
提醒一下...如果您只是将其粘贴到当前代码中,这将不起作用。必须从头开始,否则重做。