добавил базовый элемент описания, внес базовые настройки для корректного отображения текста
88 lines
3.4 KiB
TypeScript
88 lines
3.4 KiB
TypeScript
import { _decorator, Component, Label, Node, UITransform } from 'cc';
|
||
const { ccclass, property } = _decorator;
|
||
|
||
@ccclass('AutoLineBreaker')
|
||
export class AutoLineBreaker extends Component {
|
||
@property(Label)
|
||
public label: Label | null = null;
|
||
|
||
@property
|
||
public maxWidth: number = 300; // Максимальная ширина строки в пикселях
|
||
|
||
start() {
|
||
if (this.label) {
|
||
this.label.string = this.breakText(this.label.string);
|
||
}
|
||
}
|
||
|
||
breakText(text: string): string {
|
||
// Разбиваем исходный текст по пробелам
|
||
const words = text.split(' ');
|
||
let result = '';
|
||
let currentLine = '';
|
||
|
||
for (let i = 0; i < words.length; i++) {
|
||
const word = words[i];
|
||
// Если уже есть текст в строке, добавляем пробел перед следующим словом
|
||
const testLine = currentLine.length > 0 ? currentLine + ' ' + word : word;
|
||
const width = this.measureTextWidth(testLine);
|
||
|
||
if (width > this.maxWidth) {
|
||
// Если текущая строка пуста, значит слово само по себе слишком длинное
|
||
if (currentLine === '') {
|
||
// Разбиваем длинное слово по символам
|
||
result += this.breakLongWord(word) + '\n';
|
||
} else {
|
||
// Завершаем текущую строку и начинаем новую со словом
|
||
result += currentLine + '\n';
|
||
// Если слово само по себе превышает лимит, разбиваем его
|
||
if (this.measureTextWidth(word) > this.maxWidth) {
|
||
result += this.breakLongWord(word) + '\n';
|
||
currentLine = '';
|
||
} else {
|
||
currentLine = word;
|
||
}
|
||
}
|
||
} else {
|
||
currentLine = testLine;
|
||
}
|
||
}
|
||
// Добавляем остаток строки
|
||
if (currentLine.length > 0) {
|
||
result += currentLine;
|
||
}
|
||
return result;
|
||
}
|
||
|
||
breakLongWord(word: string): string {
|
||
let result = '';
|
||
let currentSegment = '';
|
||
for (let i = 0; i < word.length; i++) {
|
||
const testSegment = currentSegment + word.charAt(i);
|
||
if (this.measureTextWidth(testSegment) > this.maxWidth) {
|
||
result += currentSegment + '\n';
|
||
currentSegment = word.charAt(i);
|
||
} else {
|
||
currentSegment = testSegment;
|
||
}
|
||
}
|
||
if (currentSegment.length > 0) {
|
||
result += currentSegment;
|
||
}
|
||
return result;
|
||
}
|
||
|
||
measureTextWidth(text: string): number {
|
||
// Создаём временный узел с Label для измерения ширины
|
||
const tempNode = new Node();
|
||
const tempLabel = tempNode.addComponent(Label);
|
||
tempLabel.font = this.label!.font;
|
||
tempLabel.string = text;
|
||
tempLabel.lineHeight = this.label!.lineHeight;
|
||
tempLabel.overflow = Label.Overflow.NONE;
|
||
tempLabel.updateRenderData(true);
|
||
const uiTransform = tempLabel.node.getComponent(UITransform);
|
||
return uiTransform ? uiTransform.contentSize.width : 0;
|
||
}
|
||
}
|