How do I implement word wrap?

前端 未结 3 709
走了就别回头了
走了就别回头了 2021-01-14 02:31

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

3条回答
  •  情深已故
    2021-01-14 02:52

    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();
    }
    

提交回复
热议问题