如何使用该DrawString
功能并将其发送rectangle
(设置对齐)?如果文本比矩形的宽度长,那么该行将一直持续到行尾?(不是多行案例!!)
问问题
404 次
1 回答
1
我创建了一个扩展方法来删除水平目标区域之外的任何文本。(我假设这就是您的意思)它在文本 ( ...
) 中添加了一个选项省略号,让用户知道文本继续。
public static void DrawStringTrim(this SpriteBatch spriteBatch, SpriteFont font, Rectangle rect, string text, Color color)
{
// Characters to append to end of text, can be removed.
string ellipsis = "...";
// Get the width of the text string.
int size = (int)Math.Ceiling(font.MeasureString(text).X);
// Is text longer than the destination region? If not, simply draw it
if (size > rect.Width)
{
// Account for the length of the "..." (ellipsis) string.
int es = string.IsNullOrWhiteSpace(ellipsis) ? 0 : (int)Math.Ceiling(font.MeasureString(ellipsis).X);
for (int i = text.Length - 1; i > 0; i--)
{
int c = 1;
// Remove two letters if the preceding character is a space.
if (char.IsWhiteSpace(text[i - 1]))
{
c = 2;
i--;
}
// Chop off the tail of the string and re-measure the width.
text = text.Remove(i, c);
size = (int)Math.Ceiling(font.MeasureString(text).X);
// Text is short enough?
if (size + es <= rect.Width)
break;
}
// Append the ellipsis to the truncated string.
text += ellipsis;
}
// Draw the text
spriteBatch.DrawString(font, text, new Vector2(rect.X, rect.Y), color);
}
然后你可以画出你想要的字符串spriteBatch.DrawStringTrim(font, new Rectangle(Width, Height), "Some really really long text!", Color.White);
于 2013-11-03T16:47:32.733 回答