From 5bf111d05a22073d66e6c696f475e1dd708887d6 Mon Sep 17 00:00:00 2001 From: Ellpeck Date: Thu, 6 Feb 2020 02:27:21 +0100 Subject: [PATCH] fixed SplitString not respecting long words --- Demos/UiDemo.cs | 1 + MLEM/Extensions/SpriteFontExtensions.cs | 30 +++++++++++++++++++------ 2 files changed, 24 insertions(+), 7 deletions(-) diff --git a/Demos/UiDemo.cs b/Demos/UiDemo.cs index 9e1b7fc..c1c18da 100644 --- a/Demos/UiDemo.cs +++ b/Demos/UiDemo.cs @@ -209,6 +209,7 @@ namespace Demos { root.AddChild(ElementHelper.ImageButton(Anchor.AutoLeft, new Vector2(1, 10), tree, "Button with image")).PositionOffset = new Vector2(0, 1); root.AddChild(new Button(Anchor.AutoLeft, new Vector2(1, 10), "Disabled button") {IsDisabled = true}).PositionOffset = new Vector2(0, 1); + //root.AddChild(new Paragraph(Anchor.AutoLeft, 1, "This_is_a_really_long_line_to_see_if_splitting_without_spaces_works_properly._I_also_want_to_see_if_it_works_across_multiple_lines_or_just_on_the_first_one. But after this, I want the text to continue normally before changing_back_to_being_really_long_oh_yes")); // Below are some querying examples that help you find certain elements easily diff --git a/MLEM/Extensions/SpriteFontExtensions.cs b/MLEM/Extensions/SpriteFontExtensions.cs index 8b55de2..88b0cb5 100644 --- a/MLEM/Extensions/SpriteFontExtensions.cs +++ b/MLEM/Extensions/SpriteFontExtensions.cs @@ -29,17 +29,33 @@ namespace MLEM.Extensions { return total.ToString(); } - public static string SplitString(Func widthFunc, string text, float width, float scale) { + public static string SplitString(Func widthFunc, string text, float width, float scale) { var total = new StringBuilder(); foreach (var line in text.Split('\n')) { var curr = new StringBuilder(); foreach (var word in line.Split(' ')) { - curr.Append(word).Append(' '); - if (widthFunc(curr) * scale >= width) { - var len = curr.Length - word.Length - 1; - if (len > 0) { - total.Append(curr.ToString(0, len - 1)).Append('\n'); - curr.Remove(0, len); + if (widthFunc(word) * scale >= width) { + if (curr.Length > 0) { + total.Append(curr.ToString(0, curr.Length - 1)).Append('\n'); + curr.Clear(); + } + var wordBuilder = new StringBuilder(); + for (var i = 0; i < word.Length; i++) { + wordBuilder.Append(word[i]); + if (widthFunc(wordBuilder.ToString()) * scale >= width) { + total.Append(wordBuilder.ToString(0, wordBuilder.Length - 1)).Append('\n'); + wordBuilder.Remove(0, wordBuilder.Length - 1); + } + } + curr.Append(wordBuilder).Append(' '); + } else { + curr.Append(word).Append(' '); + if (widthFunc(curr.ToString()) * scale >= width) { + var len = curr.Length - word.Length - 1; + if (len > 0) { + total.Append(curr.ToString(0, len - 1)).Append('\n'); + curr.Remove(0, len); + } } } }