RichTextAutoResize.ts 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. import { _decorator, Component, RichText, Node, UITransform } from 'cc';
  2. const { ccclass, property } = _decorator;
  3. @ccclass('RichTextAutoFontSize')
  4. export class RichTextAutoFontSize extends Component {
  5. @property({ type: RichText })
  6. richText: RichText = null;
  7. start() {
  8. this.adjustFontSize();
  9. }
  10. adjustFontSize() {
  11. if (!this.richText) {
  12. console.warn('RichText component not found!');
  13. return;
  14. }
  15. const parentTransform = this.node.parent.getComponent(UITransform);
  16. const richTextTransform = this.richText.node.getComponent(UITransform);
  17. if (!parentTransform || !richTextTransform) {
  18. console.warn('UITransform component not found!');
  19. return;
  20. }
  21. while (richTextTransform.width > parentTransform.width || richTextTransform.height > parentTransform.height) {
  22. this.richText.fontSize--;
  23. // 强制更新渲染
  24. this.richText.enabled = false;
  25. this.richText.enabled = true;
  26. // 重新获取更新后的宽高
  27. richTextTransform.width = this.richText.node.getComponent(UITransform).width;
  28. richTextTransform.height = this.richText.node.getComponent(UITransform).height;
  29. }
  30. }
  31. }