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