public void DrawText(string str, Vector2 drawpos, Alignment alignment, TextParameters parameters) { parameters = parameters.Copy(); int lineoffset = 0; int totalindex = 0; str = FontUtil.FitString(str, parameters); foreach (string line in str.Split('\n')) { if (lineoffset + parameters.LineSeperator > parameters.MaxHeight) { break; } int textwidth = FontUtil.GetStringWidth(line, parameters); int offset = (parameters.MaxWidth ?? 0) - textwidth; switch (alignment) { case (Alignment.Left): offset = 0; break; case (Alignment.Center): offset /= 2; break; } DrawTextLine(line, drawpos + new Vector2(offset, lineoffset), totalindex, parameters); totalindex += line.Length; lineoffset += parameters.LineSeperator; } }
public static string FitString(string str, TextParameters parameters) { parameters = parameters.Copy(); int maxwidth = parameters.MaxWidth ?? int.MaxValue; int lastspot = 0; int idealspot = 0; int width = 0; string newstr = ""; for (int i = 0; i < str.Length; i++) { char chr = str[i]; var charWidth = GetCharWidth(chr) + parameters.CharSeperator + (parameters.Bold ? 1 : 0); if (charWidth > maxwidth) { return(""); } width += charWidth; switch (chr) { case (Game.FORMAT_BOLD): parameters.Bold = !parameters.Bold; break; } if (chr == ' ') { idealspot = i + 1; } if (chr == '\n') { width = 0; } if (width > maxwidth) { if (idealspot == lastspot) { idealspot = i; } string substr = str.Substring(lastspot, idealspot - lastspot); newstr += substr.Trim() + "\n"; lastspot = idealspot; i = idealspot - 1; width = 0; } } newstr += str.Substring(lastspot, str.Length - lastspot); return(newstr); }
public static int GetStringWidth(string str, TextParameters parameters) { parameters = parameters.Copy(); int n = 0; foreach (char chr in str) { n += GetCharWidth(chr) + parameters.CharSeperator + (parameters.Bold ? 1 : 0); switch (chr) { case (Game.FORMAT_BOLD): parameters.Bold = !parameters.Bold; break; } } return(n); }