BitmapFont.ts 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. this._string = value + "";
  30. for (let i = 0; i < this.string.length; i++) {
  31. let child = this.node.children[i];
  32. const chair = this.string[i];
  33. let data = this.getData(chair);
  34. if (data) {
  35. if (child) {
  36. child.active = true;
  37. child.getComponent(Sprite).spriteFrame = data.spriteFrame;
  38. }
  39. else {
  40. let node = new Node(chair);
  41. node.layer = this.node.layer;
  42. let sprite = node.addComponent(Sprite);
  43. sprite.spriteFrame = data.spriteFrame;
  44. node.parent = this.node;
  45. }
  46. }
  47. else {
  48. Log.error(`BitmapFont中缺少字符 ${chair} 的配置。`)
  49. }
  50. }
  51. for (let i = this.string.length; i < this.node.children.length; i++) {
  52. const child = this.node.children[i];
  53. child.active = false;
  54. }
  55. }
  56. private getData(chair: string) {
  57. for (let j = 0; j < this.dataList.length; j++) {
  58. const data = this.dataList[j];
  59. if (data.chair == chair) {
  60. return data;
  61. }
  62. }
  63. return null;
  64. }
  65. }