creator3.x实现扩散涂色

creator3.x实现扩散涂色

1、声明两个map,用来缓存可涂色的像素点

/**涂色像素点列表 */
private _map: Map<number, number> = new Map();
/**每帧涂色列表 */
private _mapTemp: Map<number, number> = new Map();

2、声明绘制Texutre2D

    //纹理数据设置给精灵
    this._drawTexture2D = new cc.Texture2D();
    this._drawTexture2D.reset({ width: this._width, height: this._height, format: this.drawImg.spriteFrame.texture.getPixelFormat() });

3、点击监听

onTouchStart(event: cc.EventTouch) {
    let p = event.getUILocation();
    let transform = this.node.getComponent(cc.UITransform)!;
    let nodePos = transform.convertToNodeSpaceAR(cc.v3(p.x, p.y));
    //原点在左上角
    let originPos = cc.v3(nodePos.x + transform.width / 2, transform.height / 2 - nodePos.y);
    // console.log("originPos = ", originPos);

    //点击的像素点
    let x = Math.floor(originPos.x);
    let y = Math.floor(originPos.y);
    //取到点击点被包围区域
    this._map.clear();
    this._mapTemp.clear();
    this._potList.push([x, y]);
}

4、update中检测可绘制的点和进行绘制

update() {
    let flag = false;
    let count = 0;

    while (this._potList.length >= 1 && count <= 50000) {
        flag = true;
        let pot = this._potList.shift();
        if (pot[0] >= 0 && pot[0] < this._width && pot[1] >= 0 && pot[1] < this._height) {
            this.checkPot(pot[0], pot[1]);
        }
        count++;
    }

    if (flag && this._drawTexture2D) {
        for (const [key, value] of this._mapTemp.entries()) {
            for (let n = 0; n < 4; n++) {
                this._drawTexuture[key * 4 + n] = this._figureTexture[key * 4 + n];
            }
        }
        this._mapTemp.clear();
        this._drawTexture2D.uploadData(this._drawTexuture);
        this.drawImg.spriteFrame.texture = this._drawTexture2D;
    }
}

5、检测像素点

/**检测像素点 */
checkPot(x: number, y: number) {
    let idx = (y * this._width + x);
    if (!this._map.has(idx)) {
        this._map.set(idx, 1);
        this._mapTemp.set(idx, 1);
        if (this._gfxTexture[idx * 4] > 200) {
            this._potList.push([x - 1, y]);
            this._potList.push([x + 1, y]);
            this._potList.push([x, y - 1]);
            this._potList.push([x, y + 1]);
        }
    }
}

获取图片像素信息请参考:
https://blog.csdn.net/lnn0904/article/details/134579083

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值