BitmapFont.ts 2.0 KB

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