为什么我们需要一个loading界面呢?这是因为当我们切换场景的时候,第二个scene初始化完毕但是第一个scene还没被释放的时候,内存会达到一个峰值,这个时候有可能会收到内存警告甚至是程序crash。为了避免这种情况,最好是在关卡切换或者说切换layer时,做一个loadingLayer来过渡。下面我们就利用上一篇文章的成果来做一个loading界面吧!

在loading界面中使用进度条

//loading场景的头文件
#ifndef _LOADING_SCENE_H_
#define _LOADING_SCENE_H_
#include "cocos2d.h"
using namespace cocos2d;

class LoadingScene: public CCLayer
{
public:
	bool init();
	static CCScene * scene();
	CREATE_FUNC(LoadingScene);
	//异步加载图片调用的函数
	void loadingCallBack(CCObject * object);
private:
	//设置加载图片的总数
	int m_totalNum;
	//以加载图片的数量
	int m_loadedNum;
	//俩个文本信息
	CCLabelAtlas * m_atlas;
	CCLabelTTF * m_labelLoading;
	CCProgressTimer * m_progress;
};
#endif
//loading场景的具体实现
#include "LoadingScene.h"
#include "HelloWorldScene.h"

CCScene * LoadingScene::scene()
{
	CCScene * scene = NULL;
	do
	{
		scene = CCScene::create();
		CC_BREAK_IF(!scene);
		LoadingScene * layer = LoadingScene::create();
		CC_BREAK_IF(!layer);
		scene->addChild(layer);
	}
	while(0);

	return scene;
}

bool LoadingScene::init()
{
	CCSize size = CCDirector::sharedDirector()->getWinSize();
	//初始化类的成员变量
	this->m_totalNum = 100;
	this->m_loadedNum = 0;
	this->m_atlas = CCLabelAtlas::create("0","fps_images.png",12,32,'.');
	this->m_labelLoading = CCLabelTTF::create("Loading...","Arial",24);
	//设置属性
	this->m_atlas->setPosition(ccp(size.width/2,size.height*0.3));
	this->m_labelLoading->setPosition(ccp(size.width/2,size.height/2));
	this->addChild(this->m_atlas);
	this->addChild(this->m_labelLoading);

	this->m_progress = CCProgressTimer::create(CCSprite::create("progress.jpg"));
	this->m_progress->setPosition(ccp(size.width/2,size.height*0.2));
	//设置类型
	m_progress->setType(kCCProgressTimerTypeBar);
	//设置图片精灵变化的方向
	m_progress->setBarChangeRate(ccp(1,0));
	//设置起始变化的点
	m_progress->setMidpoint(ccp(0,0));
	this->addChild(m_progress);

	//这里的代码是用来加载图片的,到时候把你需要加载的图片都写到这里面
	for(int i=0;i<100;i++)
	{
		//addImageAsync异步加载图片
		CCTextureCache::sharedTextureCache()->addImageAsync("HelloWorld.png",this,
			callfuncO_selector(LoadingScene::loadingCallBack));
	}

	return true;
}

void LoadingScene::loadingCallBack(CCObject * object)
{
	this->m_loadedNum++;
	//获得加载的图片占图片总数的百分比
	float percentage = (float)this->m_loadedNum/this->m_totalNum*100;
	//设置图片的显示比例
	this->m_progress->setPercentage(percentage);
	CCString * string = CCString::createWithFormat("%d",this->m_loadedNum);
	this->m_atlas->setString(string->getCString());

	if(this->m_loadedNum == this->m_totalNum)
	{
		//加载完毕切换场景
		CCDirector::sharedDirector()->replaceScene(HelloWorld::scene());
	}
}

下面来看看在下一个场景中如何使用loading场景加载的图片。

//从缓存中获得图片
	CCTexture2D * background = CCTextureCache::sharedTextureCache()->textureForKey("HelloWorld.png");
	CCSprite * sprite = CCSprite::createWithTexture(background);
	sprite->setPosition(ccp(visibleSize.width/2,visibleSize.height/2));
	this->addChild(sprite);

记得在场景释放的时候将缓存中的图片删除!

HelloWorld::~HelloWorld()
{
	//在析构函数中需要删除缓存中不需要的图片
	CCTextureCache::sharedTextureCache()->removeUnusedTextures();
}