81 lines
2.0 KiB
TypeScript
81 lines
2.0 KiB
TypeScript
const {
|
||
ccclass,
|
||
property,
|
||
executeInEditMode,
|
||
requireComponent,
|
||
disallowMultiple,
|
||
} = cc._decorator;
|
||
|
||
/**
|
||
* 给当前节点上的 cc.Label 添加可调节的黑色描边。
|
||
*
|
||
* 使用方法:
|
||
* 1. 将本脚本挂到带有 cc.Label 的节点上。
|
||
* 2. 在属性检查器中修改 Outline Width。
|
||
* 3. 运行时可调用 setOutlineWidth(width) 修改描边厚度。
|
||
*
|
||
* 注意:cc.LabelOutline 只支持系统字体和 TTF 字体,不支持 BMFont。
|
||
*/
|
||
@ccclass
|
||
@executeInEditMode
|
||
@requireComponent(cc.Label)
|
||
@disallowMultiple
|
||
export default class LabelBlackOutline extends cc.Component {
|
||
@property({
|
||
type: cc.Integer,
|
||
min: 0,
|
||
max: 20,
|
||
step: 1,
|
||
slide: true,
|
||
tooltip: "黑色描边厚度,0 表示不显示描边",
|
||
})
|
||
outlineWidth: number = 2;
|
||
|
||
private _lastWidth: number = -1;
|
||
|
||
protected onLoad(): void {
|
||
this.applyOutline();
|
||
}
|
||
|
||
protected onEnable(): void {
|
||
this.applyOutline();
|
||
}
|
||
|
||
protected update(): void {
|
||
// executeInEditMode 下可在编辑器中实时预览厚度变化。
|
||
if (this._lastWidth !== this.outlineWidth) {
|
||
this.applyOutline();
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 运行时修改描边厚度。
|
||
*/
|
||
public setOutlineWidth(width: number): void {
|
||
this.outlineWidth = Math.max(0, Math.round(width));
|
||
this.applyOutline();
|
||
}
|
||
|
||
/**
|
||
* 立即将当前配置应用到 cc.LabelOutline。
|
||
*/
|
||
public applyOutline(): void {
|
||
if (!this.node) {
|
||
return;
|
||
}
|
||
|
||
let outline = this.node.getComponent(cc.LabelOutline);
|
||
if (!outline) {
|
||
outline = this.node.addComponent(cc.LabelOutline);
|
||
}
|
||
|
||
const width = Math.max(0, Math.round(this.outlineWidth));
|
||
this.outlineWidth = width;
|
||
outline.color = cc.Color.BLACK;
|
||
outline.width = width;
|
||
outline.enabled = width > 0;
|
||
|
||
this._lastWidth = width;
|
||
}
|
||
}
|