cocos2dx wp8 纹理缓存
wp8下纹理缓存CCTextureCache不会在系统空闲时释放导致内存只增不减
手动调用CCTextureCache::removeUnusedTextures后,内存不足发生的概率大大降低
下面代码实现了当纹理总像素大小到达一定数目之上后,手动调用removeUnusedTextures释放问题
本来想以程序使用的总内存为标准,但是wp8下相关的Microsoft.Phone.Info.DeviceStatus只能在c#下用,就先用总像素数做个近似吧
注意在计算完像素数后必须调用removeAllObjects()来释放snapshotTextures()获得的字典的所有元素,否则会导致removeUnusedTextures()无用
因为字典会增加元素的引用计数
static void checkAndFreeMemory()
{
#ifdef _WP8
CCTextureCache* cache = CCTextureCache::sharedTextureCache();
CCDictionary* cachedTextures = cache->snapshotTextures();
if (cachedTextures == NULL || cachedTextures->count() <= 5)
return;
// estimate total texture pixel count
long long size = 0;
CCDictElement* pElement = NULL;
CCDICT_FOREACH(cachedTextures, pElement)
{
CCTexture2D *value = (CCTexture2D*)pElement->getObject();
const CCSize& sz = value->getContentSizeInPixels();
size += sz.width * sz.height;
}
cachedTextures->removeAllObjects();
if (size < 1024L * 1024L * 5L)
return;
cache->removeUnusedTextures();
#endif
}

浙公网安备 33010602011771号