static CCSprite* CCSprite::create(const char *pszFileName)的簡單分析
CCSpriteBatchNoded,CCSpriteFrameCache的簡單分析
我的版本:cocos2d-2.0-rc2-x-2.0.1
本人理解有誤之處,希望看官不吝指出。
1 static CCSprite* CCSprite::create(const char *pszFileName)的簡單分析
一個CCSprite對象的主要成員是CCTexture2D對象。
create方法產生CCSprite對象的步驟爲:先new一個CCSprite對象,然後調用CCSprite的初始化方法:initWithFile(pszFileName)。下面是create方法。
CCSprite* CCSprite::create(const char *pszFileName) { CCSprite *pobSprite = new CCSprite(); if (pobSprite && pobSprite->initWithFile(pszFileName)) { pobSprite->autorelease(); return pobSprite; } CC_SAFE_DELETE(pobSprite); return NULL; }
而初始化方法的目的主要是填充新產生的CCSprite對象的CCTextture2D成員。這個成員實際上是通過CCTextureCache來獲得。下面是初始化方法。
bool CCSprite::initWithFile(const char *pszFilename) { CCAssert(pszFilename != NULL, "Invalid filename for sprite"); CCTexture2D *pTexture = CCTextureCache::sharedTextureCache()->addImage(pszFilename); if (pTexture) { CCRect rect = CCRectZero; rect.size = pTexture->getContentSize(); return initWithTexture(pTexture, 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; }
CCTextureCache::sharedTextureCache()->addImage(pszFilename)獲得CCTexture2D對象的過程:通過pszFilename查詢CCTextureCache內部保存的所有CCTexture2D對象,如果有,則直接返回,沒有,則生成一個。如果是新生成一個CCTexture2D對象,那麼就會涉及到讀文件操作。
2 CCSpriteBatchNoded,CCSpriteFrameCache的簡單分析
CCSpriteBatchNoded的一般使用方法是:利用CCSpriteFrameCache添加plist文件,然後通過CCSpriteFrameByName引用。下面是添加方法。
void CCSpriteFrameCache::addSpriteFramesWithFile(const char* plist, const char* textureFileName) { CCAssert(textureFileName, "texture name should not be null"); CCTexture2D *texture = CCTextureCache::sharedTextureCache()->addImage(textureFileName); if (texture) { addSpriteFramesWithFile(plist, texture); } else { CCLOG("cocos2d: CCSpriteFrameCache: couldn't load texture file. File not found %s", textureFileName); } }
添加的方法是:通過CCtextreCache獲得plist文件對應的大圖的CCTextrue2D。之後通過plist文件所記錄的信息,把大圖邏輯上拆分成多個共享CCTextrue2D的CCSpriteFrame,並以鍵值對的形式保存在CCSpriteFrameCache裏面。
獲得CCSpriteFrame的方法是:通過CCSpriteFrameCahce的CCSpriteFrameByName方法,來找到對應的CCSprieteFrame。這個時候,每次產生的CCSpriteFrame都是之前那張大圖,只是邏輯上是獲得該大圖的不同區域而已。
使用CCSpriteBatchNoded的主要目的是優化性能。
主要注意點:
1 添加到ccspriteBatchNode裏面的精靈的紋理必須與產生CCSpriteBatchNode對象的紋理是同樣的。
2 添加到ccspriteBatchNode裏面的精靈的深度相對於外部都是一樣的,如果要有不同深度的效果,那麼可能要放置在不同的ccspriteBatchNode裏面來實現。