Files
18xchat/assets/Scripts/chat18x/ui/components/DialogBubble.ts
T

81 lines
2.2 KiB
TypeScript
Raw Normal View History

2025-08-15 18:17:12 +08:00
import {
_decorator,
Component,
Label,
Node,
Overflow,
Size,
UITransform,
} from "cc";
2025-08-11 16:08:59 +08:00
import Tools from "../../utils/tools";
2025-07-21 22:14:06 +08:00
const { ccclass, property } = _decorator;
@ccclass("DialogBubble")
export class DialogBubble extends Component {
@property(UITransform)
bg: UITransform = null;
@property(Label)
content: Label = null;
@property(UITransform)
contentT: UITransform = null;
2025-08-15 18:17:12 +08:00
fixMaxWidth: number;
init(maxWidth: number = 650) {
this.fixMaxWidth = maxWidth;
}
2025-08-13 12:55:27 +08:00
updateBubbleContent(str: string, callback?: (actualHeight: number) => void) {
2025-08-15 18:17:12 +08:00
this.content.overflow = Overflow.NONE;
2025-08-13 12:55:27 +08:00
// 设置文本内容
2025-07-21 22:14:06 +08:00
this.content.string = str;
2025-08-13 12:55:27 +08:00
// 计算最大宽度(估算)
const lines = str.split("\n");
let maxWidth = 0;
2025-07-21 22:14:06 +08:00
2025-08-13 12:55:27 +08:00
for (const line of lines) {
let lineWidth = 0;
if (Tools.IsChinese(line)) {
2025-08-15 18:17:12 +08:00
lineWidth = 30 * line.length;
2025-08-13 12:55:27 +08:00
} else {
2025-08-15 18:17:12 +08:00
lineWidth = 18 * line.length;
2025-08-13 12:55:27 +08:00
}
maxWidth = Math.max(maxWidth, lineWidth);
}
2025-08-15 18:17:12 +08:00
if (maxWidth > this.fixMaxWidth)
this.content.overflow = Overflow.RESIZE_HEIGHT;
2025-08-13 12:55:27 +08:00
// 限制最大宽度
2025-08-15 18:17:12 +08:00
const contentWidth = Math.min(maxWidth, this.fixMaxWidth);
2025-08-13 12:55:27 +08:00
// 设置内容区域宽度,让Label自动计算高度
this.contentT.setContentSize(new Size(contentWidth, 0));
2025-08-15 18:17:12 +08:00
this.bg.setContentSize(new Size(contentWidth + 17, 0));
2025-08-13 12:55:27 +08:00
// 强制更新Label的渲染数据以获取正确的高度
this.content.updateRenderData(true);
// 等待一帧后获取Label的实际高度
this.scheduleOnce(() => {
2025-08-15 18:17:12 +08:00
const actualSize =
this.content.node.getComponent(UITransform).contentSize;
2025-08-13 12:55:27 +08:00
// 更新内容区域的实际大小
2025-08-15 18:17:12 +08:00
//this.contentT.setContentSize(new Size(contentWidth, actualHeight));
2025-08-13 12:55:27 +08:00
// 根据内容大小调整背景大小,添加适当的内边距
2025-08-15 18:17:12 +08:00
//const bgHeight = actualHeight + 17;
this.bg.setContentSize(new Size(actualSize.x + 30, actualSize.y + 10));
2025-08-13 12:55:27 +08:00
// 回调通知实际高度
if (callback) {
2025-08-15 18:17:12 +08:00
callback(actualSize.y);
2025-08-13 12:55:27 +08:00
}
}, 0);
// 返回预估的背景高度(用于同步计算)
const estimatedHeight = Math.max(lines.length * 35 + 20, 60); // 最小高度60
return estimatedHeight;
2025-07-21 22:14:06 +08:00
}
}