32 lines
2.0 KiB
TypeScript
32 lines
2.0 KiB
TypeScript
const { ccclass } = cc._decorator;
|
|
|
|
/** Numeric content is ALWAYS source sprites. Missing glyphs are reported, never replaced by Label. */
|
|
@ccclass
|
|
export default class PyramidDigits extends cc.Component {
|
|
private signature = "";
|
|
set(value: string | number, frames: { [key: string]: cc.SpriteFrame }, height: number, maxWidth = 1000, commonScale = false): void {
|
|
const text = String(value), signature = text + ":" + height + ":" + maxWidth + ":" + commonScale;
|
|
if (signature === this.signature) return;
|
|
const missing = text.split("").filter(c => !frames[c]);
|
|
if (missing.length) { this.clear(); this.signature = ""; cc.warn("[Pyramid] 缺失数字素材", missing.join(",")); return; }
|
|
this.signature = signature; this.clear();
|
|
const referenceHeight = commonScale ? frames["0"].getRect().height : 0;
|
|
const widths = text.split("").map(c => { const r = frames[c].getRect(); return height * r.width / (referenceHeight || r.height); });
|
|
const total = widths.reduce((n, w) => n + w, 0) + Math.max(0, text.length - 1) * 1.5;
|
|
const scale = Math.min(1, maxWidth / Math.max(1, total)); let left = -total / 2;
|
|
text.split("").forEach((c, i) => {
|
|
const glyph = new cc.Node("Digit_" + c); this.node.addChild(glyph);
|
|
const sprite = glyph.addComponent(cc.Sprite);
|
|
sprite.sizeMode = cc.Sprite.SizeMode.CUSTOM;
|
|
sprite.spriteFrame = frames[c];
|
|
const glyphHeight = commonScale ? height * frames[c].getRect().height / referenceHeight : height;
|
|
glyph.setContentSize(widths[i], glyphHeight);
|
|
glyph.setPosition(left + widths[i] / 2, (glyphHeight - height) / 2);
|
|
left += widths[i];
|
|
// left += widths[i] + 1.5;
|
|
});
|
|
this.node.setContentSize(total, height); this.node.setScale(scale);
|
|
}
|
|
private clear(): void { this.node.children.slice().forEach(child => child.destroy()); this.node.removeAllChildren(); }
|
|
}
|