Created
May 15, 2013 17:12
-
-
Save hjerpbakk/5585584 to your computer and use it in GitHub Desktop.
Simple text wrapping using MonoGame / XNA.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private string WrapText(string text) { | |
if(font.MeasureString(text).X < MaxLineWidth) { | |
return text; | |
} | |
string[] words = text.Split(' '); | |
StringBuilder wrappedText = new StringBuilder(); | |
float linewidth = 0f; | |
float spaceWidth = font.MeasureString(" ").X; | |
for(int i = 0; i < words.Length; ++i) { | |
Vector2 size = font.MeasureString(words[i]); | |
if(linewidth + size.X < MaxLineWidth) { | |
linewidth += size.X + spaceWidth; | |
} else { | |
wrappedText.Append("\n"); | |
linewidth = size.X + spaceWidth; | |
} | |
wrappedText.Append(words[i]); | |
wrappedText.Append(" "); | |
} | |
return wrappedText.ToString(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks mate, that saved me a lot of time.