This commit is contained in:
2025-08-13 12:55:27 +08:00
parent db0b040fd8
commit 53e2687546
4 changed files with 89 additions and 58 deletions
@@ -11,47 +11,54 @@ export class DialogBubble extends Component {
@property(UITransform)
contentT: UITransform = null;
updateBubbleContent(str: string) {
const lines = str.split("\n");
let len = 0;
let index = 0;
for (let i = 0; i < lines.length; i++) {
const element = lines[i];
if (element.length > len) {
len = element.length;
index = i;
}
}
let finalLen = 0;
// for (let i = 0; i < lines[index].length; i++) {
// const element = lines[index][i];
// if ("\u4e00" <= element[i] && element[i] <= "\u9fff") {
// finalLen += 35;
// } else {
// finalLen += 18;
// }
// }
if (Tools.IsChinese(lines[index])) {
finalLen = 35 * lines[index].length;
} else {
finalLen = 21 * lines[index].length;
}
updateBubbleContent(str: string, callback?: (actualHeight: number) => void) {
// 设置文本内容
this.content.string = str;
this.contentT.setContentSize(
new Size(Math.min(finalLen, 950), this.contentT.contentSize.y)
);
this.content.updateRenderData();
this.bg.setContentSize(
new Size(
this.contentT.contentSize.x + 30,
this.contentT.contentSize.y + 20
)
);
// 计算最大宽度(估算)
const lines = str.split("\n");
let maxWidth = 0;
return this.bg.contentSize.y;
for (const line of lines) {
let lineWidth = 0;
if (Tools.IsChinese(line)) {
lineWidth = 35 * line.length;
} else {
lineWidth = 21 * line.length;
}
maxWidth = Math.max(maxWidth, lineWidth);
}
// 限制最大宽度
const contentWidth = Math.min(maxWidth, 950);
// 设置内容区域宽度,让Label自动计算高度
this.contentT.setContentSize(new Size(contentWidth, 0));
this.bg.setContentSize(new Size(contentWidth + 20, 0));
// 强制更新Label的渲染数据以获取正确的高度
this.content.updateRenderData(true);
// 等待一帧后获取Label的实际高度
this.scheduleOnce(() => {
const actualHeight =
this.content.node.getComponent(UITransform).contentSize.height;
// 更新内容区域的实际大小
this.contentT.setContentSize(new Size(contentWidth, actualHeight));
// 根据内容大小调整背景大小,添加适当的内边距
const bgHeight = actualHeight + 20;
this.bg.setContentSize(new Size(contentWidth + 50, bgHeight));
// 回调通知实际高度
if (callback) {
callback(bgHeight);
}
}, 0);
// 返回预估的背景高度(用于同步计算)
const estimatedHeight = Math.max(lines.length * 35 + 20, 60); // 最小高度60
return estimatedHeight;
}
}