BitmapFont.ts 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import { Component, Node, Sprite, SpriteFrame, _decorator } from "cc";
  2. import { Log } from "../utils/Log";
  3. const { ccclass, property } = _decorator;
  4. /**
  5. * 字符集数据
  6. */
  7. @ccclass("BitmapFontData")
  8. export class BitmapFontData {
  9. @property({ tooltip: "字符" })
  10. public chair: string = '';
  11. @property({ tooltip: "图片", type: SpriteFrame })
  12. public spriteFrame: SpriteFrame;
  13. }
  14. /**
  15. * 位图文本
  16. * @author 袁浩
  17. */
  18. @ccclass("BitmapFont")
  19. export class BitmapFont extends Component {
  20. @property({ tooltip: "字符集配置", type: [BitmapFontData] })
  21. public dataList: BitmapFontData[] = [];
  22. @property({ visible: false })
  23. private _string: string = '';
  24. @property({ tooltip: "文本内容字符串", serializable: true })
  25. public get string(): string {
  26. return this._string;
  27. }
  28. public set string(value: string) {
  29. if(value == 'undefined'){
  30. Log.error(`字符出错${value}`);
  31. return;
  32. }
  33. this._string = value + "";
  34. for (let i = 0; i < this.string.length; i++) {
  35. let child = this.node.children[i];
  36. const chair = this.string[i];
  37. let data = this.getData(chair);
  38. if (data) {
  39. if (child) {
  40. child.active = true;
  41. child.getComponent(Sprite).spriteFrame = data.spriteFrame;
  42. }
  43. else {
  44. let node = new Node(chair);
  45. node.layer = this.node.layer;
  46. let sprite = node.addComponent(Sprite);
  47. sprite.spriteFrame = data.spriteFrame;
  48. node.parent = this.node;
  49. }
  50. }
  51. else {
  52. Log.error(`BitmapFont中缺少字符 ${chair} 的配置。`)
  53. }
  54. }
  55. for (let i = this.string.length; i < this.node.children.length; i++) {
  56. const child = this.node.children[i];
  57. child.active = false;
  58. }
  59. }
  60. private getData(chair: string) {
  61. for (let j = 0; j < this.dataList.length; j++) {
  62. const data = this.dataList[j];
  63. if (data.chair == chair) {
  64. return data;
  65. }
  66. }
  67. return null;
  68. }
  69. }