1
0
Fork 0
mirror of https://github.com/Ellpeck/MLEM.git synced 2024-11-25 14:08:34 +01:00

allow adding ellipsis to truncatestring

This commit is contained in:
Ellpeck 2020-04-11 15:44:55 +02:00
parent d5ce920e52
commit e4ba2bc38f
2 changed files with 10 additions and 3 deletions

View file

@ -49,8 +49,9 @@ namespace MLEM.Font {
this.DrawString(batch, text, position, color, rotation, origin, scale, effects, layerDepth); this.DrawString(batch, text, position, color, rotation, origin, scale, effects, layerDepth);
} }
public string TruncateString(string text, float width, float scale, bool fromBack = false) { public string TruncateString(string text, float width, float scale, bool fromBack = false, string ellipsis = "") {
var total = new StringBuilder(); var total = new StringBuilder();
var ellipsisWidth = this.MeasureString(ellipsis).X * scale;
for (var i = 0; i < text.Length; i++) { for (var i = 0; i < text.Length; i++) {
if (fromBack) { if (fromBack) {
total.Insert(0, text[text.Length - 1 - i]); total.Insert(0, text[text.Length - 1 - i]);
@ -58,8 +59,8 @@ namespace MLEM.Font {
total.Append(text[i]); total.Append(text[i]);
} }
if (this.MeasureString(total).X * scale >= width) if (this.MeasureString(total).X * scale + ellipsisWidth >= width)
return total.ToString(fromBack ? 1 : 0, total.Length - 1); return total.Remove(fromBack ? 0 : total.Length - 1, 1).Append(ellipsis).ToString();
} }
return total.ToString(); return total.ToString();
} }

View file

@ -96,6 +96,12 @@ namespace Sandbox {
font.DrawString(this.SpriteBatch, "Right Aligned\nover multiple lines", new Vector2(640, 200), TextAlign.Right, Color.White); font.DrawString(this.SpriteBatch, "Right Aligned\nover multiple lines", new Vector2(640, 200), TextAlign.Right, Color.White);
font.DrawString(this.SpriteBatch, "Center Aligned on both axes", new Vector2(640, 360), TextAlign.CenterBothAxes, Color.White); font.DrawString(this.SpriteBatch, "Center Aligned on both axes", new Vector2(640, 360), TextAlign.CenterBothAxes, Color.White);
this.SpriteBatch.Draw(this.SpriteBatch.GetBlankTexture(), new Rectangle(640 - 4, 360 - 4, 8, 8), Color.Green); this.SpriteBatch.Draw(this.SpriteBatch.GetBlankTexture(), new Rectangle(640 - 4, 360 - 4, 8, 8), Color.Green);
this.SpriteBatch.Draw(this.SpriteBatch.GetBlankTexture(), new Rectangle(200, 400, 200, 400), Color.Green);
font.DrawString(this.SpriteBatch, font.TruncateString("This is a very long string", 200, 1), new Vector2(200, 400), Color.White);
font.DrawString(this.SpriteBatch, font.TruncateString("This is a very long string", 200, 1, ellipsis: "..."), new Vector2(200, 450), Color.White);
font.DrawString(this.SpriteBatch, font.TruncateString("This is a very long string", 200, 1, true), new Vector2(200, 500), Color.White);
font.DrawString(this.SpriteBatch, font.TruncateString("This is a very long string", 200, 1, true, "..."), new Vector2(200, 550), Color.White);
this.SpriteBatch.End(); this.SpriteBatch.End();
}; };
} }