实现思路:
1、查找当前内存中的所有贴图:cc.textureCache._textures
2、当前正在使用的贴图:通过当前场景,遍历所有的子节点,查找引用的贴图
3、遍历所有的贴图,看下是否正在使用
// 获取指定节点的下的所有子节点(包含自己)
var getAllChildren = function(curr) {
var stack = [curr];
var index = 0
while (curr) {
// Walk through children
children = curr._children;
if (children && children.length > 0) {
for (i = 0, len = children.length; i < len; ++i) {
child = children[i];
stack.push(child);
}
}
children = curr._protectedChildren;
if (children && children.length > 0) {
for (i = 0, len = children.length; i < len; ++i) {
child = children[i];
stack.push(child);
}
}
index++;
curr = stack[index];
}
return stack;
}
// 检查没有用到的贴图
var checkNoUseTexture = function () {
var arrChildren = getAllChildren(cc.director.getRunningScene());
// 当前正在使用的贴图
var dInUseUrl = {};
for (var i = 0, iLen = arrChildren.length; i < iLen; i++) {
if (arrChildren[i]._texture && arrChildren[i]._texture.url) {
dInUseUrl[arrChildren[i]._texture.url] = 1;
}
}
// 遍历内存中所有的贴图
for (var key in cc.textureCache._textures) {
// 正在使用
if (dInUseUrl[key]) {
continue;
}
var selTexture = cc.textureCache._textures[key];
var iBytes = selTexture.getPixelsWide() * selTexture.getPixelsHigh() * 4;
var iMInfo = (iBytes / (1024.0 * 1024.0)).toFixed(2)
// 尺寸大小、内存信息
cc.warn(key, selTexture.getPixelsWide(), selTexture.getPixelsHigh(), iMInfo)
}
}
// 调用
checkNoUseTexture();