yantar/assets/Scripts/core/AutoLineBreak.ts
Georgy Shive f29ed605a0 Добавил шрифты в проект,
добавил базовый элемент описания,
внес базовые настройки для
корректного отображения текста
2025-03-07 01:06:16 +07:00

88 lines
3.4 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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;
}
}