richtext.check.ts 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. import { _decorator, CCFloat, Component, RichText, UITransform } from 'cc';
  2. const { ccclass, property } = _decorator;
  3. /**
  4. * 富文本检查
  5. * 还在测试开发中
  6. */
  7. @ccclass('RichTextCheck')
  8. export class RichTextCheck extends Component {
  9. @property(CCFloat)
  10. private height: number = 0;
  11. @property(CCFloat)
  12. private width: number = 0;
  13. private richtext: RichText;
  14. private ui: UITransform
  15. private originFontSize: number;
  16. private originLineHeight: number;
  17. protected onLoad(){
  18. this.ui = this.node.getComponent(UITransform);
  19. this.richtext = this.node.getComponent(RichText);
  20. this.originFontSize = this.richtext.fontSize;
  21. this.originLineHeight = this.richtext.lineHeight;
  22. this.adaptFontSize();
  23. }
  24. private text: string;
  25. private calculating: boolean = false;
  26. private max_full_size: number;
  27. private min_full_size: number;
  28. private limit_size: number = 0;
  29. private _adapt_np_: mtec.NudityPromise<'end'>;
  30. protected lateUpdate(dt: number): void {
  31. if(this.richtext.string!=this.text) this.adaptFontSize();
  32. if(this.calculating) this.calculateFontSize();
  33. }
  34. private calculateFontSize(){
  35. if(this.ui.width > this.width || this.ui.height > this.height){
  36. this.max_full_size = this.richtext.fontSize;
  37. }else{
  38. this.min_full_size = this.richtext.fontSize;
  39. }
  40. let size = mtec.number.fixedNum((this.max_full_size + this.min_full_size) / 2, 2);
  41. let line_height = mtec.number.fixedNum(size * this.originLineHeight / this.originFontSize, 2);
  42. this.richtext.fontSize = size;
  43. this.richtext.lineHeight = line_height;
  44. this.calculating = (this.max_full_size-this.min_full_size) > 0.02;
  45. if(!this.calculating){
  46. this.limit_size = Math.min(this.limit_size, this.min_full_size);
  47. let np = this._adapt_np_;
  48. this._adapt_np_ = null;
  49. np.resolve('end');
  50. }
  51. }
  52. private adaptFontSize(){
  53. this.text = this.richtext.string;
  54. this.max_full_size = this.originFontSize;
  55. this.min_full_size = this.limit_size;
  56. let np = this._adapt_np_;
  57. this._adapt_np_ = new mtec.NudityPromise();
  58. if(np) this._adapt_np_.promise.then(()=>np.resolve('end'));
  59. this.calculating = true;
  60. }
  61. public forceAdatptFontSize(active: boolean){
  62. this.node.active = true;
  63. this.adaptFontSize();
  64. this._adapt_np_.promise.then(()=>this.node.active = active);
  65. return this._adapt_np_.promise;
  66. }
  67. public adaptThen<R>(callback?: ()=>R){
  68. let p = this._adapt_np_ ? this._adapt_np_.promise : undefined;
  69. return Promise.resolve(p).then(callback)
  70. }
  71. }