cocos creator 2.1.1 版本不使用mask对图片进行裁切
因项目需求需要在不增加drawcall的情况下将一整张图裁切成N个小图片。
原理
因为不能增加drawcall所以我们不能使用mask组件。但我们可以从SpriteFrame下手,SpriteFrame其实是Texture + Rect 得到的。知道这个原理我们可以着手下一步了。
代码
我们可以创建多个有相同texture的spriteframe,在根据Rect对其进行裁剪。
cc.Class({
extends: cc.Component,
properties: {
texture_pic : cc.SpriteFrame,
node_cut: cc.Sprite,
},
// LIFE-CYCLE CALLBACKS:
onLoad () {
//获取texture纹理
let tx = this.texture_pic.getTexture();
//根据纹理创建一个spriteframe
let cutPic = new cc.SpriteFrame(tx);
//对其进行裁切 左上角为0,0点 裁切一个长宽各100的尺寸
cutPic.setRect(new cc.Rect(0,0,100,100));
this.node_cut.spriteFrame = cutPic;
},
start () {
},
// update (dt) {},
});
root节点里是未经我们用Rect进行裁切的原始图片样子,而cut节点是我们将图片以左上角为锚点,长宽各裁剪100后将spriteframe赋值的节点。接下来我们运行上述代码
上图中下方的小图片就是我们对上图进行裁切的结果。因为图片共用一个texture所以drawcall并未增加。
拓展
根据上述步骤我们可以对其进行拓展,将原图拆分成3x5的小图,代码如下:
cc.Class({
extends: cc.Component,
properties: {
texture_pic : cc.SpriteFrame,
// node_root: cc.Node,
prefab_cut: cc.Prefab,
node_layout: cc.Node,
},
// LIFE-CYCLE CALLBACKS:
onLoad () {
let sp = this.texture_pic.getTexture();
//根据3x5的需求进行裁切图片
for (let i=0;i<3;i++) {
for (let j=0;j<5;j++) {
let cutPic = new cc.SpriteFrame(sp);
cutPic.setRect(new cc.Rect(j*94.8,i*105.33,94.8,105.33));
//实例化cut预制体
this._initPrefab(cutPic);
}
}
},
_initPrefab (sp) {
let temp = cc.instantiate(this.prefab_cut);
//利用layout组件进行布局
temp.parent = this.node_layout;
temp.getComponent(cc.Sprite).spriteFrame = sp;
},
start () {
},
// update (dt) {},
});
运行后结果如下:
drawcall也未明显增加。