今天想封装个东西,需要代码动态创建一个纯色底,发现并没有矩形精灵类
没有外部资源,也不能用graphic或者自绘
谁知道吗
/**
* 绘制纯色方块
*
* @static
* @memberof UITools
*/
public static DrawColorRect(size: cc.Rect , color: cc.Color = cc.Color.BLACK): cc.Node
{
let node = new cc.Node(‘colorRect’);
node.setContentSize(size);
let graph = node.addComponent(cc.Graphics);
graph.fillColor = color || new cc.Color(0, 0, 0, 255 * 0.6);
graph.fillRect(size.x, size.y, size.width, size.height);
return node;
}
2赞
多谢你的方法
我还是更偏向于写个通用组件来处理这样的事情(这样既可以在代码里动态创建,也可以在编辑器里实时预览)
const { ccclass, property, requireComponent, executeInEditMode } = cc._decorator;
@ccclass
@requireComponent(cc.Graphics)
@executeInEditMode
export default class ColorLayer extends cc.Component {
private _drawGraphics: cc.Graphics;
static create(name: string = "colorLayer", size: cc.Size = cc.size(200, 200), color: cc.Color = cc.Color.WHITE): cc.Node {
let node = new cc.Node(name);
node.addComponent(ColorLayer);
node.setContentSize(size);
node.color = color;
return node;
}
onLoad() {
CC_EDITOR && this.node.on(cc.Node.EventType.SIZE_CHANGED, this.applayChanged.bind(this), this);
CC_EDITOR && this.node.on(cc.Node.EventType.COLOR_CHANGED, this.applayChanged.bind(this), this);
CC_EDITOR && this.node.on(cc.Node.EventType.ANCHOR_CHANGED, this.applayChanged.bind(this), this);
}
start() {
this.applayChanged();
}
applayChanged() {
this.drawGraphics.fillColor = this.node.color;
this.drawGraphics.clear();
this.drawGraphics.fillRect(0 - this.node.width * this.node.anchorX, 0 - this.node.height * this.node.anchorY, this.node.width, this.node.height);
}
get drawGraphics() {
if (!this._drawGraphics) {
this._drawGraphics = this.node.getComponent(cc.Graphics);
if (!this._drawGraphics) {
this._drawGraphics = this.node.addComponent(cc.Graphics);
}
}
return this._drawGraphics;
}
}
1赞
你的方法让我对组件一些玩法有了更深的认识
mark
mark