如何实现自动换行? [英] How do I implement word wrap?
本文介绍了如何实现自动换行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
XNA有SpriteFont类类,它有一个MeasureString方法,它可以返回宽度和字符串
的高度。我想了解如何创建插在正确的地方的方法,这将有效地 Environment.Newline
返回一个字符串,因此,如果符合一定的宽度和高度( 。矩形作为一个参数)
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 that will efficiently return a string with Environment.Newline
inserted in the right places, so that if fits a certain Width and Height (Rectangle is used as a parameter for that).
推荐答案
我发现下面的代码:的 XNA - 基本的文字包装
I found following code: XNA - Basic Word Wrapping
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();
}
这篇关于如何实现自动换行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文