Skip to content

Commit 2a6f2e1

Browse files
committed
Make line wrapping split words
1 parent 68462cc commit 2a6f2e1

File tree

1 file changed

+49
-16
lines changed

1 file changed

+49
-16
lines changed

Assets/Scripts/OpenTS2/UI/Skia/SkiaLabel.cs

Lines changed: 49 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -62,33 +62,66 @@ private void Render()
6262

6363
private void DrawText(SKCanvas canvas, SKPaint paint, SKImageInfo imageInfo)
6464
{
65-
var splitText = Text.Split(' ');
66-
var wrappedLines = new List<string>();
67-
var lineLength = 0f;
68-
var line = "";
69-
foreach(var word in splitText)
65+
var lines = new List<string>();
66+
var lastCharWasSpace = false;
67+
var lastWordIndex = -1;
68+
var lastLineIndex = 0;
69+
for(var i = 0; i < Text.Length; i++)
7070
{
71-
var wordWithSpace = $"{word} ";
72-
var wordWithSpaceLength = paint.MeasureText(wordWithSpace);
73-
if (lineLength + wordWithSpaceLength > imageInfo.Width)
71+
var c = Text[i];
72+
if (c == ' ')
7473
{
75-
wrappedLines.Add(line);
76-
line = wordWithSpace;
77-
lineLength = wordWithSpaceLength;
74+
if (!lastCharWasSpace)
75+
lastWordIndex = i;
76+
lastCharWasSpace = true;
7877
}
7978
else
8079
{
81-
line += wordWithSpace;
82-
lineLength += wordWithSpaceLength;
80+
lastCharWasSpace = false;
81+
var currentText = Text.Substring(lastLineIndex, (i + 1) - lastLineIndex);
82+
var length = paint.MeasureText(currentText);
83+
if (length > imageInfo.Width)
84+
{
85+
var cutText = currentText.Substring(0, currentText.Length - 1);
86+
if (lastWordIndex != -1)
87+
{
88+
var textAtLastWord = Text.Substring(lastLineIndex, lastWordIndex - lastLineIndex);
89+
var lastWordLength = paint.MeasureText(textAtLastWord);
90+
if (lastWordLength <= imageInfo.Width)
91+
{
92+
lines.Add(textAtLastWord);
93+
lastLineIndex = lastWordIndex + 1;
94+
lastWordIndex = -1;
95+
lastCharWasSpace = false;
96+
}
97+
else
98+
{
99+
lines.Add(cutText);
100+
lastLineIndex = i;
101+
lastWordIndex = -1;
102+
lastCharWasSpace = false;
103+
}
104+
}
105+
else
106+
{
107+
lines.Add(cutText);
108+
lastLineIndex = i;
109+
lastWordIndex = -1;
110+
lastCharWasSpace = false;
111+
}
112+
}
83113
}
84114
}
85115

86-
wrappedLines.Add(line);
116+
var lastLineLength = Text.Length - lastLineIndex;
117+
if (lastLineLength > 0)
118+
{
119+
lines.Add(Text.Substring(lastLineIndex));
120+
}
87121

88122
var y = FontSize;
89-
foreach (var wrappedLine in wrappedLines)
123+
foreach (var wrappedLine in lines)
90124
{
91-
Debug.Log(wrappedLine);
92125
canvas.DrawText(wrappedLine, 0f, y, paint);
93126
y += FontSize;
94127
}

0 commit comments

Comments
 (0)