| 12345678910111213141516171819202122232425262728293031323334353637383940 |
- import { _decorator, Component, RichText, Node, UITransform } from 'cc';
- const { ccclass, property } = _decorator;
- @ccclass('RichTextAutoFontSize')
- export class RichTextAutoFontSize extends Component {
- @property({ type: RichText })
- richText: RichText = null;
- start() {
- this.adjustFontSize();
- }
- adjustFontSize() {
- if (!this.richText) {
- console.warn('RichText component not found!');
- return;
- }
- const parentTransform = this.node.parent.getComponent(UITransform);
- const richTextTransform = this.richText.node.getComponent(UITransform);
- if (!parentTransform || !richTextTransform) {
- console.warn('UITransform component not found!');
- return;
- }
- while (richTextTransform.width > parentTransform.width || richTextTransform.height > parentTransform.height) {
- this.richText.fontSize--;
- // 强制更新渲染
- this.richText.enabled = false;
- this.richText.enabled = true;
- // 重新获取更新后的宽高
- richTextTransform.width = this.richText.node.getComponent(UITransform).width;
- richTextTransform.height = this.richText.node.getComponent(UITransform).height;
- }
- }
- }
|