cocos2dx学习笔记之三种缓存类TextureCache,SpriteFrameCache,AnimationCache

Cocos引擎有3个缓存类:TextureCache,SpriteFrameCache,AnimationCache;

使用缓存类的目的是为了当加载一次图片资源后,再次使用此资源可以从内存中访问,而不是从磁盘读取图片,起到重复利用第一次加载,减少CPU负担的作用。

这3个缓存类分别维护各自的map容器对象:

 TextureCache: std::unordered_map<std::string, Texture2D*> _textures;

SpriteFrameCache:  Map<std::string, SpriteFrame*> _spriteFrames;ValueMap _spriteFramesAliases;std::set<std::string>*  _loadedFileNames;

AnimationCache: Map<std::string, Animation*> _animations;

以Texture2D * TextureCache::addImage(const std::string &path)为例,最重要的一行就是执行  _textures.insert( std::make_pair(fullpath, texture) );

在容器中插入一个元素。

那么直接通过Sprite::create("fileName")创建一次精灵后,再次创建相同纹理的精灵是否会遵循从内存读取纹理,不从磁盘读取的规则呢?答案是肯定的

Sprite* Sprite::create(const std::string& filename)
{
    Sprite *sprite = new (std::nothrow) Sprite();
    if (sprite && sprite->initWithFile(filename))
    {
        sprite->autorelease();
        return sprite;
    }
    CC_SAFE_DELETE(sprite);
    return nullptr;
}
bool Sprite::initWithFile(const std::string& filename)
{
    if (filename.empty())
    {
        CCLOG("Call Sprite::initWithFile with blank resource filename.");
        return false;
    }

    _fileName = filename;
    _fileType = 0;

    Texture2D *texture = Director::getInstance()->getTextureCache()->addImage(filename);
    if (texture)
    {
        Rect rect = Rect::ZERO;
        rect.size = texture->getContentSize();
        return initWithTexture(texture, rect);
    }

    // don't release here.
    // when load texture failed, it's better to get a "transparent" sprite then a crashed program
    // this->release();
    return false;
}
可以看到会间接调用
Texture2D *texture = Director::getInstance()->getTextureCache()->addImage(filename);
纹理缓存类将图片对象保存到其_textures容器对象中去,由此可以看到这两种创建精灵的方式是等价的

Sprite* sprite1 = Sprite::create("fileName.png");
Texture2D* texture2 = Director::getInstance()->getTextureCache()->addImage("fileName.png");
Sprite* sprite2 = Sprite::createWithTexture(texture2);
可以得出结论,即使你写的代码中没有和这3个缓存类相关的代码,只要通过代码加载图片就会间接的使用这些缓存类了。


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ellis1970

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值