From e4ba2bc38f93265385d475352274c71c2cb4234b Mon Sep 17 00:00:00 2001 From: Ellpeck Date: Sat, 11 Apr 2020 15:44:55 +0200 Subject: [PATCH] allow adding ellipsis to truncatestring --- MLEM/Font/GenericFont.cs | 7 ++++--- Sandbox/GameImpl.cs | 6 ++++++ 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/MLEM/Font/GenericFont.cs b/MLEM/Font/GenericFont.cs index 0f01fea..0e82361 100644 --- a/MLEM/Font/GenericFont.cs +++ b/MLEM/Font/GenericFont.cs @@ -49,8 +49,9 @@ namespace MLEM.Font { 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 ellipsisWidth = this.MeasureString(ellipsis).X * scale; for (var i = 0; i < text.Length; i++) { if (fromBack) { total.Insert(0, text[text.Length - 1 - i]); @@ -58,8 +59,8 @@ namespace MLEM.Font { total.Append(text[i]); } - if (this.MeasureString(total).X * scale >= width) - return total.ToString(fromBack ? 1 : 0, total.Length - 1); + if (this.MeasureString(total).X * scale + ellipsisWidth >= width) + return total.Remove(fromBack ? 0 : total.Length - 1, 1).Append(ellipsis).ToString(); } return total.ToString(); } diff --git a/Sandbox/GameImpl.cs b/Sandbox/GameImpl.cs index f374f8f..1e722f1 100644 --- a/Sandbox/GameImpl.cs +++ b/Sandbox/GameImpl.cs @@ -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, "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(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(); }; }