Skip to content

Instantly share code, notes, and snippets.

@hjerpbakk
Created May 15, 2013 17:12
Show Gist options
  • Save hjerpbakk/5585584 to your computer and use it in GitHub Desktop.
Save hjerpbakk/5585584 to your computer and use it in GitHub Desktop.
Simple text wrapping using MonoGame / XNA.
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();
}
@mth0348
Copy link

mth0348 commented Jan 23, 2018

Thanks mate, that saved me a lot of time.

@joeqnicholson
Copy link

ditto, thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment