找物源码导读Cocos Creator 3.8 · assets/scripts
0%
已读 0 / 424
目录— 个文件
目录加载中…
…/module/component/SpriteFonts.ts
1import { _decorator, CCFloat, Color, Component, Layers, Node, Sprite, SpriteAtlas, SpriteFrame, UITransform } from 'cc';
2import { EDITOR } from 'cc/env';
3const { ccclass, property, executeInEditMode } = _decorator;
4
5// ==================== FontItem ====================
6
7@ccclass('FontItem')
8class FontItems {
9 // 字符串默认值已提供属性类型,避免重复声明导致编辑器警告。
10 @property({ displayName: "显示字符" })
11 public string = "";
12
13 @property(SpriteFrame)
14 private _sf: SpriteFrame = null!;
15
16 @property({ type: CCFloat, displayName: "x轴偏移" })
17 public xOffset: number = 0;
18
19 @property({ type: CCFloat, displayName: "y轴偏移" })
20 public yOffset: number = 0;
21
22 @property({ type: SpriteFrame, displayName: "图片" })
23 set sf(value) {
24 if (!value) return;
25 if (!(value instanceof SpriteFrame)) return;
26 this._sf = value;
27 if (!this.string && this._sf.name && this._sf.name.length > 0)
28 this.string = this._sf.name[this._sf.name.length - 1];
29 }
30 get sf() { return this._sf; }
31
32 get width() { return this.sf.originalSize.width; }
33 get height() { return this.sf.originalSize.height; }
34}
35
36// ==================== SpriteFonts ====================
37
38@ccclass('SpriteFonts')
39@executeInEditMode
40export class SpriteFonts extends Component {
41
42 @property
43 private _space: number = 0;
44 @property
45 set space(value) {
46 if (this._space == value) return;
47 this._space = value;
48 this.updateView();
49 }
50 get space() { return this._space; }
51
52 @property
53 private _isAltlas: boolean = false;
54 @property
55 set isAltlas(v: boolean) {
56 if (typeof v === 'undefined') return;
57 if (v == this._isAltlas) return;
58 this._isAltlas = v;
59 }
60 get isAltlas() { return this._isAltlas; }
61
62 @property(SpriteAtlas)
63 private _spriteAltas: SpriteAtlas = null!;
64 @property({ type: SpriteAtlas, visible: function (this: SpriteFonts) { return this.isAltlas } })
65 set spriteAltas(value) {
66 if (this._spriteAltas === value) return;
67 this._spriteAltas = value;
68 if (!this.items || this.items.length == 0) {
69 let allSf = this._spriteAltas.spriteFrames;
70 for (let i in allSf) {
71 let sf = allSf[i];
72 if (sf) {
73 let item = new FontItems();
74 item.sf = sf;
75 !this.items && (this.items = []);
76 this.items.push(item);
77 }
78 }
79 }
80 this.updateView();
81 }
82 get spriteAltas() { return this._spriteAltas; }
83
84 @property({ type: [FontItems] })
85 private items: FontItems[] = [];
86
87 @property
88 private _isGray: boolean = false;
89 @property
90 set isGray(value) {
91 if (this._isGray == value) return;
92 this._isGray = value;
93 this.updateView();
94 }
95 get isGray() { return this._isGray; }
96
97 @property
98 private _string: string = "";
99 @property
100 set string(value) {
101 if (this._string == value) return;
102 this._string = value;
103 this.unschedule(this.updateView);
104 this.scheduleOnce(this.updateView);
105 }
106 get string() { return this._string; }
107
108 @property(Color)
109 private _color: Color = new Color(255, 255, 255);
110 @property(Color)
111 set color(value) {
112 if (this._color.equals(value)) return;
113 this._color.set(value);
114 this.updateView();
115 }
116 get color() { return this._color; }
117
118 // ==================== 缓存 ====================
119
120 protected itemStringList: { [key: string]: FontItems } = null!;
121 private _idleNodes: Node[] = [];
122
123 // ==================== 生命周期 ====================
124
125 protected __preload(): void {
126 super.__preload?.();
127 this.recycleAllChildren();
128 }
129
130 protected onLoad(): void {
131 this.recycleAllChildren();
132 this.updateView();
133 }
134
135 onDestroy(): void {
136 this.recycleAllChildren();
137 this._idleNodes.forEach((n) => { if (n.isValid) n.destroy(); });
138 this._idleNodes.length = 0;
139 }
140
141 /** 将所有当前子节点回收到 _idleNodes */
142 private recycleAllChildren(): void {
143 const children = [...this.node.children];
144 for (const child of children) {
145 child.active = false;
146 child.removeFromParent();
147 this._idleNodes.push(child);
148 }
149 }
150
151 // ==================== 渲染 ====================
152
153 async updateView() {
154 const chars = this._string.split("");
155 const targetCount = chars.length;
156
157 this.matchChildCount(targetCount);
158
159 let last = 0;
160 let totalWidth = 0;
161 let maxHeight = 0;
162 let firstItemWidth = 0;
163 const thisTrans = this.getComponent(UITransform)!;
164 const parentLayer = this.node.layer;
165
166 for (let i = 0; i < targetCount; i++) {
167 const item = this.getItem(chars[i]);
168 if (!item) continue;
169
170 const child = this.node.children[i];
171 // 保证子节点与父节点同层
172 child.layer = parentLayer;
173
174 const sp = child.getComponent(Sprite)!;
175 if (this.isAltlas && this.spriteAltas) {
176 sp.spriteAtlas = this.spriteAltas;
177 }
178 sp.color = this.color;
179 sp.spriteFrame = item.sf;
180 sp.grayscale = this._isGray;
181
182 if (i > 0) {
183 last += item.width / 2;
184 } else {
185 firstItemWidth = item.width;
186 }
187 totalWidth += (item.width + this.space);
188 child.setPosition(last + item.xOffset, item.yOffset, 0);
189 last += item.width / 2 + this.space;
190 maxHeight = Math.max(maxHeight, item.height);
191 }
192
193 totalWidth -= this.space;
194 const offset = -(totalWidth / 2) + firstItemWidth / 2
195 - (thisTrans.anchorX - 0.5) * thisTrans.width;
196 for (let i = this.node.children.length - 1; i >= 0; i--) {
197 const child = this.node.children[i];
198 child.setPosition(child.position.x + offset, child.position.y, child.position.z);
199 }
200 thisTrans.setContentSize(totalWidth, maxHeight);
201 }
202
203 // ==================== 子节点管理 ====================
204
205 private matchChildCount(targetCount: number): void {
206 while (this.node.children.length > targetCount) {
207 const last = this.node.children[this.node.children.length - 1];
208 last.active = false;
209 last.removeFromParent();
210 this._idleNodes.push(last);
211 }
212
213 while (this.node.children.length < targetCount) {
214 let child: Node;
215 if (this._idleNodes.length > 0) {
216 child = this._idleNodes.pop()!;
217 child.active = true;
218 } else {
219 child = this.createCharNode();
220 }
221 child.setParent(this.node);
222 }
223 }
224
225 private createCharNode(): Node {
226 const node = new Node('fontChar');
227 node.addComponent(UITransform).setContentSize(0, 0);
228 node.addComponent(Sprite);
229 return node;
230 }
231
232 // ==================== 字符查找 ====================
233
234 getItem(str: string): FontItems | undefined {
235 if (!this.itemStringList) {
236 this.itemStringList = {};
237 for (let item of this.items) {
238 if (item.string && item.sf) {
239 this.itemStringList[item.string] = item;
240 }
241 }
242 }
243 const item = this.itemStringList[str];
244 if (EDITOR) this.itemStringList = null!;
245 return item;
246 }
247}
讲解248 行
图片文字人工通读

SpriteFonts.ts

组件把字符串拆成字符,按映射的 SpriteFrame 生成居中排布的精灵子节点,尺寸与偏移取字符配置。多余节点进入实例空闲池,销毁统一释放;运行态字符映射首次建立后不再刷新,未知字符跳过赋图,复用节点可能保留旧画面。

先看 updateView 的字符循环和宽度计算,再看节点池及 getItem 的编辑器差异。

特殊处理与易错点

  • 易错点缺失字符映射时 continue,复用出来的该位置子节点可能仍显示旧帧。
  • 缓存运行时 itemStringList 只在首次查找时建立,修改 items 不会自动失效。
  • 特殊处理空字符串计算总宽为负字间距,且锚点偏移使用更新前的节点宽度。
  • 销毁初始化会回收全部已有子节点,不只组件自行创建的字符节点。
10注释字符串默认值已提供属性类型,避免重复声明导致编辑器警告。
14属性sf(SpriteFrame):该模块的运行态字段。
17属性x Offset(number):该模块的运行态字段。
20属性y Offset(number):该模块的运行态字段。
22方法接受有效纹理帧并在未设字符时从帧名末字补映射。
32方法读取字符图片的原始宽度供图片文字横向排布计算。
33方法读取字符图片的原始高度供图片文字最大高度计算。
40注释FontItems:将所有当前子节点回收到 _idleNodes
43属性space(number):该模块的运行态字段。
44方法字符间隔变化时保存新值并立即重新排布全部字符。
53属性是否 Altlas(boolean):该模块的运行态字段。
54方法切换图片文字的图集模式标记而不立即刷新现有节点。
63属性sprite Altas(SpriteAtlas):该模块的运行态字段。
64方法保存图集并在没有映射项时从图集帧建立字符配置。
85属性项(FontItems[]):该模块的运行态字段。
88属性是否 Gray(boolean):该模块的运行态字段。
89方法灰度开关变化时保存状态并立即刷新所有字符精灵。
98属性string(string):该模块的运行态字段。
99方法保存新文字并合并为下一次调度刷新避免同帧重复排布。
109属性color(Color):该模块的运行态字段。
110方法复制新颜色到组件持有对象并立即刷新字符精灵颜色。
120属性字符到 FontItems 的索引;运行时持久缓存,编辑器每次查找后失效。
121属性已移除父节点的字符节点池,缩短文字时入池,增长时复用。
125方法执行基类预加载后把节点当前所有子节点移入空闲池。
130方法再次回收现有子节点并按当前字符串重新创建字符画面。
135方法回收全部当前字符并销毁空闲池内仍有效的节点。
142方法将当前所有子节点禁用脱离父节点后存入空闲池。
153方法匹配字符节点数量并按帧尺寸偏移颜色重新排布文字。
172注释保证子节点与父节点同层
205方法回收多余字符节点或从空闲池取节点补足目标数量。
225方法创建带 UITransform 与 Sprite 的空字符节点供排布。
234方法建立字符映射后查询目标配置并在编辑器中清掉缓存。