1、精灵创建
/**
* Creates a sprite with an image filename.
*/
static CCSprite* create(const char *pszFileName);
-->>
CCSprite* CCSprite::create(const char *pszFileName)
{
CCSprite *pobSprite = new CCSprite();
//初始化函数initWithFile -->>
if (pobSprite && pobSprite->initWithFile(pszFileName))
{
pobSprite->autorelease();
return pobSprite;
}
CC_SAFE_DELETE(pobSprite);
return NULL;
}
-->>
bool CCSprite::initWithFile(const char *pszFilename)
{
CCAssert(pszFilename != NULL, "Invalid filename for sprite");
//根据图片文件名,得到对应的CCTexture2D
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 than a crashed program
// this->release();
return false;
}
-------initWithTexture-------->>
initWithTexture调用setTexture函数,设置CCTexture2D
setTexture(pTexture);
void CCSprite::setTexture(CCTexture2D *texture)
{
// If batchnode, then texture id should be the same
CCAssert(! m_pobBatchNode || texture->getName() == m_pobBatchNode->getTexture()->getName(), "CCSprite: Batched sprites should use the same texture as the batchnode");
// accept texture==nil as argument
CCAssert( !texture || dynamic_cast<CCTexture2D*>(texture), "setTexture expects a CCTexture2D. Invalid argument");
if (NULL == texture)
{
// Gets the texture by key firstly.
texture = CCTextureCache::sharedTextureCache()->textureForKey(CC_2x2_WHITE_IMAGE_KEY);
// If texture wasn't in cache, create it from RAW data.
if (NULL == texture)
{
CCImage* image = new CCImage();
bool isOK = image->initWithImageData(cc_2x2_white_image, sizeof(cc_2x2_white_image), CCImage::kFmtRawData, 2, 2, 8);
CCAssert(isOK, "The 2x2 empty texture was created unsuccessfully.");
texture = CCTextureCache::sharedTextureCache()->addUIImage(image, CC_2x2_WHITE_IMAGE_KEY);
CC_SAFE_RELEASE(image);
}
}
if (!m_pobBatchNode && m_pobTexture != texture)
{
CC_SAFE_RETAIN(texture);
CC_SAFE_RELEASE(m_pobTexture); //这里会对texture的引用计数加1
m_pobTexture = texture;
updateBlendFunc();
}
}
2、精灵释放:
CCSprite::~CCSprite(void)
{
CC_SAFE_RELEASE(m_pobTexture); //这里会对texture的引用计数减1
}
精灵创建源码分析
最新推荐文章于 2018-10-12 11:50:51 发布