Text Clipping

From XNAWiki
Jump to: navigation, search

This method may be useful to make sure that you dont draw text across some borders on your screen, and where you have a limited amount of space within which to draw text.

The following function will clip the text to the nearest character on a single line.

public string ClipText(SpriteFont font, string text, int Width, int pixelBuffer)
      {
            int charIndex = text.Length;
            string textToWrite = text.Substring(0, charIndex);
 
            Vector2 fontDimensions = font.MeasureString(textToWrite);
 
            while (fontDimensions.X > Width - (pixelBuffer * 2))
            {
                charIndex--;
                textToWrite = text.Substring(0, charIndex);
                fontDimensions = font.MeasureString(textToWrite);
            }
 
            return textToWrite;            
      }

You can clip text to the nearest word on multiple lines by using a modified version of the Basic Word Wrapping method.

public string WrapText(SpriteFont spriteFont, string text, float maxLineWidth, float maxTextHeight)
	{
		string[] words = text.Split(' ');
 
		StringBuilder sb = new StringBuilder();
 
		float lineWidth = 0f;
		float textHeight = 0f;
 
		float spaceWidth = spriteFont.MeasureString(" ").X;
 
		textHeight = spaceWidth.Y;
 
		foreach (string word in words)
		{
			Vector2 size = spriteFont.MeasureString(word);
 
			if (lineWidth + size.X < maxLineWidth)
			{
				sb.Append(word + " ");
				lineWidth += size.X + spaceWidth;
			}
			else
			{
				if (maxTextHeight == null ||
				    textHeight + size.Y < maxTextHeight)
				{
					sb.Append("\n" + word + " ");
					lineWidth = size.X + spaceWidth;
					textHeight += size.Y;
				}
				else
				{
					break;
				}
			}
		}
 
		return sb.ToString();
	}