Skip to content

Commit

Permalink
Fix text wrap bug (galacean#1644)
Browse files Browse the repository at this point in the history
* fix(text): fix text measure text with wrap
---------

Co-authored-by: GuoLei1990 <[email protected]>
  • Loading branch information
singlecoder and GuoLei1990 authored Jul 19, 2023
1 parent fbb1852 commit e34cb6a
Showing 1 changed file with 22 additions and 4 deletions.
26 changes: 22 additions & 4 deletions packages/core/src/2d/text/TextUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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;
Expand All @@ -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
Expand Down

0 comments on commit e34cb6a

Please sign in to comment.