From e34cb6a61b08324591392070a99bedbcb9833526 Mon Sep 17 00:00:00 2001 From: singlecoder Date: Wed, 19 Jul 2023 14:06:46 +0800 Subject: [PATCH] Fix text wrap bug (#1644) * fix(text): fix text measure text with wrap --------- Co-authored-by: GuoLei1990 --- packages/core/src/2d/text/TextUtils.ts | 26 ++++++++++++++++++++++---- 1 file changed, 22 insertions(+), 4 deletions(-) diff --git a/packages/core/src/2d/text/TextUtils.ts b/packages/core/src/2d/text/TextUtils.ts index 1210deea27..e22fa890e8 100644 --- a/packages/core/src/2d/text/TextUtils.ts +++ b/packages/core/src/2d/text/TextUtils.ts @@ -110,6 +110,11 @@ export class TextUtils { subFont.nativeFontString = fontString; for (let i = 0, n = subTexts.length; i < n; i++) { const subText = subTexts[i]; + // If subText is empty, push an empty line directly + if (subText.length === 0) { + this._pushLine(lines, lineWidths, lineMaxSizes, "", 0, 0, 0); + continue; + } let word = ""; let wordWidth = 0; @@ -144,7 +149,11 @@ export class TextUtils { // If it is a word before, need to handle the previous word and line if (word.length > 0) { if (lineWidth + wordWidth > wrapWidth) { - this._pushLine(lines, lineWidths, lineMaxSizes, line, lineWidth, lineMaxAscent, lineMaxDescent); + // Push if before line is not empty + if (lineWidth > 0) { + this._pushLine(lines, lineWidths, lineMaxSizes, line, lineWidth, lineMaxAscent, lineMaxDescent); + } + textWidth = Math.max(textWidth, lineWidth); notFirstLine = true; line = word; @@ -191,7 +200,12 @@ export class TextUtils { line = ""; lineWidth = lineMaxAscent = lineMaxDescent = 0; } - this._pushLine(lines, lineWidths, lineMaxSizes, word, wordWidth, wordMaxAscent, wordMaxDescent); + + // Push if before word is not empty + if (wordWidth > 0) { + this._pushLine(lines, lineWidths, lineMaxSizes, word, wordWidth, wordMaxAscent, wordMaxDescent); + } + textWidth = Math.max(textWidth, wordWidth); notFirstLine = true; word = char; @@ -211,12 +225,16 @@ export class TextUtils { // If the total width from line and word exceed wrap width if (lineWidth + wordWidth > wrapWidth) { // Push chars to a single line - this._pushLine(lines, lineWidths, lineMaxSizes, line, lineWidth, lineMaxAscent, lineMaxDescent); + if (lineWidth > 0) { + this._pushLine(lines, lineWidths, lineMaxSizes, line, lineWidth, lineMaxAscent, lineMaxDescent); + } textWidth = Math.max(textWidth, lineWidth); lineWidth = 0; // Push word to a single line - this._pushLine(lines, lineWidths, lineMaxSizes, word, wordWidth, wordMaxAscent, wordMaxDescent); + if (wordWidth > 0) { + this._pushLine(lines, lineWidths, lineMaxSizes, word, wordWidth, wordMaxAscent, wordMaxDescent); + } textWidth = Math.max(textWidth, wordWidth); } else { // Merge to chars