没有修剪的DrawString

时间:2013-11-03 14:11:08

标签: c# xna drawstring

如何使用DrawString功能并发送rectangle(设置路线)?如果文本从矩形的宽度更长,那么该行将继续直到行的结尾? (不是多线情况!!)

1 个答案:

答案 0 :(得分: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);

绘制所需的字符串
相关问题