四、精灵帧类(CCSpriteFrame)
精灵帧的概念是相对于动画而产生的。一个精灵时固定的节点,它可以拥有许多精灵帧(CCSpriteFrame),在
它们之间切换就形成了动画。CCSpriteFrame类的继承关系如下图所示。
CCSpriteFrame类通过贴图定义,也可以是贴图的一部分,可以通过精灵的setDisplayFrame函数来设置当前显示
的精灵帧。它的主要函数如下图所示。
1、示例讲解
让我们来看看精灵帧类的使用方法。首先是创建精灵帧类,如下代码所示,出自tests项目中SpriteTest目录下
SpriteTest.cpp文件中SpriteAnimationSplit类中的构造函数。
- CCSpriteFrame *frame0 = CCSpriteFrame::createWithTexture(texture, CCRectMake(132*0, 132*0, 132, 132));
- CCSpriteFrame *frame1 = CCSpriteFrame::createWithTexture(texture, CCRectMake(132*1, 132*0, 132, 132));
- CCSpriteFrame *frame2 = CCSpriteFrame::createWithTexture(texture, CCRectMake(132*2, 132*0, 132, 132));
- CCSpriteFrame *frame3 = CCSpriteFrame::createWithTexture(texture, CCRectMake(132*3, 132*0, 132, 132));
- CCSpriteFrame *frame4 = CCSpriteFrame::createWithTexture(texture, CCRectMake(132*0, 132*1, 132, 132));
- CCSpriteFrame *frame5 = CCSpriteFrame::createWithTexture(texture, CCRectMake(132*1, 132*1, 132, 132));
的onExit函数。
- void SpriteAnimationSplit::onExit()
- {
- SpriteTestDemo::onExit();
- CCSpriteFrameCache::sharedSpriteFrameCache()->removeUnusedSpriteFrames();
- }
2、tests示例运行效果图。
五、精灵帧缓存类(CCSpriteFrameCache)
精灵帧缓存类CCSpriteFrameCache用来存储精灵帧,提前缓存起来有助于提高程序的效率。
CCSpriteFrameCache是一个单例模式,不属于某个精灵,是所有精灵共享使用的。
CCSpriteFrameCache类的继承关系如下图所示。
CCSpriteFrameCache类的主要函数如下图所示。
1、示例讲解
如下代码是定义和使用CCSpriteFrameCache类的函数,出自tests项目,SpriteTest目录下SpriteTest.cpp文件中
的SpriteFrameTest类中的onEnter函数。
- // CCSpriteFrameCache::sharedSpriteFrameCache()->removeUnusedSpriteFrames);
- CCSpriteFrameCache* cache = CCSpriteFrameCache::sharedSpriteFrameCache();
- cache->addSpriteFramesWithFile("animations/grossini.plist");
- cache->addSpriteFramesWithFile("animations/grossini_gray.plist", "animations/grossini_gray.png");
- cache->addSpriteFramesWithFile("animations/grossini_blue.plist", "animations/grossini_blue.png");
- //
- // Animation using Sprite BatchNode
- //
- m_pSprite1 = CCSprite::createWithSpriteFrameName("grossini_dance_01.png");
- m_pSprite1->setPosition( ccp( s.width/2-80, s.height/2) );
- CCSpriteBatchNode* spritebatch = CCSpriteBatchNode::create("animations/grossini.png");
- spritebatch->addChild(m_pSprite1);
- addChild(spritebatch);
- CCArray* animFrames = CCArray::createWithCapacity(15);
- char str[100] = {0};
- for(int i = 1; i < 15; i++)
- {
- sprintf(str, "grossini_dance_%02d.png", i);
- CCSpriteFrame* frame = cache->spriteFrameByName( str );
- animFrames->addObject(frame);
- }
的图片名称获得精灵帧缓存类CCSpriteFrameCache对象。要在onExit函数中删除这些精灵帧缓存,如下代码所示。
- void SpriteFrameTest::onExit()
- {
- SpriteTestDemo::onExit();
- CCSpriteFrameCache *cache = CCSpriteFrameCache::sharedSpriteFrameCache();
- cache->removeSpriteFramesFromFile("animations/grossini.plist");
- cache->removeSpriteFramesFromFile("animations/grossini_gray.plist");
- cache->removeSpriteFramesFromFile("animations/grossini_blue.plist");
- }
2、示例运行效果图