From 2e8b311b007aefd99b560c94ccf5001f156e4530 Mon Sep 17 00:00:00 2001 From: Ellpeck Date: Sun, 11 Aug 2019 00:39:40 +0200 Subject: [PATCH] made text fields auto-scroll once they're too full --- MLEM.Ui/Elements/TextField.cs | 21 +++++++++++++++++++-- Tests/Content/Fonts/TestFont.spritefont | 4 ++-- 2 files changed, 21 insertions(+), 4 deletions(-) diff --git a/MLEM.Ui/Elements/TextField.cs b/MLEM.Ui/Elements/TextField.cs index b012b1b..8149a67 100644 --- a/MLEM.Ui/Elements/TextField.cs +++ b/MLEM.Ui/Elements/TextField.cs @@ -20,6 +20,7 @@ namespace MLEM.Ui.Elements { public float TextOffsetX = 4; private IGenericFont font; private double caretBlinkTimer; + private int textStartIndex; public TextField(Anchor anchor, Vector2 size, IGenericFont font = null) : base(anchor, size) { this.font = font; @@ -38,8 +39,23 @@ namespace MLEM.Ui.Elements { textChanged = true; } } - if (textChanged) + if (textChanged) { + var length = this.font.MeasureString(this.Text).X * this.TextScale; + var maxWidth = this.DisplayArea.Width - this.TextOffsetX * 2; + if (length > maxWidth) { + for (var i = Math.Max(0, this.textStartIndex - 1); i < this.Text.Length; i++) { + var substring = this.Text.ToString(i, this.Text.Length - i); + if (this.font.MeasureString(substring).X * this.TextScale <= maxWidth) { + this.textStartIndex = i; + break; + } + } + } else { + this.textStartIndex = 0; + } + this.OnTextChange?.Invoke(this, this.Text.ToString()); + } }; } @@ -61,7 +77,8 @@ namespace MLEM.Ui.Elements { } batch.Draw(tex, this.DisplayArea, color); var caret = this.IsSelected && this.caretBlinkTimer >= 0.5F ? "|" : ""; - this.font.DrawCenteredString(batch, this.Text + caret, this.DisplayArea.Location.ToVector2() + new Vector2(this.TextOffsetX, this.DisplayArea.Height / 2), this.TextScale, Color.White * alpha, false, true); + var text = this.Text.ToString(this.textStartIndex, this.Text.Length - this.textStartIndex) + caret; + this.font.DrawCenteredString(batch, text, this.DisplayArea.Location.ToVector2() + new Vector2(this.TextOffsetX, this.DisplayArea.Height / 2), this.TextScale, Color.White * alpha, false, true); base.Draw(time, batch, alpha); } diff --git a/Tests/Content/Fonts/TestFont.spritefont b/Tests/Content/Fonts/TestFont.spritefont index b31c317..de8e2fe 100644 --- a/Tests/Content/Fonts/TestFont.spritefont +++ b/Tests/Content/Fonts/TestFont.spritefont @@ -11,7 +11,7 @@ with. - BitPotion + BitPotionExt - + *