Cocos2d-x Label 试用浅析

来源:互联网 发布:cms建站 手机与pc 编辑:程序博客网 时间:2024/04/30 06:17

1 CCLabelProtocol是文本标签的父类,CCLabelProtocol有三个直接子类,都是cocos2d-x中用来创建文本标签的,下面是类结构图

 

CCLabelTTF不仅是CCLabelProtocol的子类,其实也是CCSprite的子类,CCLabelTTF是用来渲染文本标签的,可以指定字体,每次设置字符串内容时,都需要重新创建纹理和渲染,性能不好,所以通常情况下使用CCLabelAtlas或者CCLabelBMFont代替。

 

CCLabelAtlas不仅是CCLabelProtocol的子类,其实也是CCAtlasNode的子类,CCAtlasNode封装了一个CCTextureAtlas的变量,CCTextureAtlas初始化图片文件的时候会把图片加载到缓存(CCTextureCache)中。CCLabelAtlas的绘制效率高,但是限制性太多,没有CCLabelBMFont灵活。

 

CCLabelBMFont不仅是CCLabelProtocol的子类,其实也是CCSpriteBatchNode的子类,创建CCLabelBMFont对象需要一个字符串和一个fnt格式的文件(字库)


下面是对对三种CCLabel的试用代码示例:

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. bool HelloWorld::init()  
  2. {  
  3.     bool bRet = false;  
  4.     do   
  5.     {  
  6.         //////////////////////////////////////////////////////////////////////////  
  7.         // super init first  
  8.         //////////////////////////////////////////////////////////////////////////  
  9.   
  10.         CC_BREAK_IF(! CCLayer::init());  
  11.   
  12.     <span style="white-space:pre">  </span>m_time = 0;  
  13.   
  14.         CCLabelTTF* Label1 = CCLabelTTF::create("Chinese human","Marker Felt",30);//第一个参数是要显示的文字,第二个是字体,<span style="white-space:pre">                                          </span>//第三个是文字大小  
  15.         Label1->setPosition(ccp(200,300));  
  16.         this->addChild(Label1);  
[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1.               //第一个参数是显示的文字,第二个是文字图片,第三个是图片里每个文字的宽度,四是高度,五是图片里第一个字符  
  2. CCLabelAtlas* label2 = CCLabelAtlas::create("5121314","tuffy_bold_italic-charmap.png",48,64,' ');  
  3. label2->setPosition(ccp(70,200));  
  4. this->addChild(label2,1,1);//设置tag为1,方便在 step 里引用  
  5. label2->setColor(ccRED);//设置字体颜色为红色  
  6.   
  7. CCActionInterval* act1 = CCFadeOut::create(0.2f);  
  8. CCActionInterval* act2 = act1->reverse();  
  9. CCSequence* seq = CCSequence::create(act1,act2,NULL);  
  10. CCAction* repeat = CCRepeatForever::create(seq);  
  11. label2->runAction( repeat );  
[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. <span style="white-space:pre">      </span>//第一个参数是显示的文字,第二个参数是字体文件  
  2.         CCLabelBMFont* label3 = CCLabelBMFont::create("itisgood","bitmapFontTest.fnt");  
  3.         label3->setPosition(ccp(70,100));  
  4.         this->addChild(label3,1,2);  
  5.   
  6.         CCSprite* BChar = (CCSprite*) label3->getChildByTag(0);//取出"itisgood"中的‘i’字符,可对它进行操作  
  7.         CCSprite* FChar = (CCSprite*) label3->getChildByTag(2);  
[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. void HelloWorld::step(float dt)  
  2. {  
  3.     m_time += dt;//定时器实时更新计数  
  4.     char time_str[12] = {0};  
  5.     sprintf(time_str,"%2.2f",m_time);  
  6.     CCLabelAtlas* label2 = (CCLabelAtlas*)this->getChildByTag(1);  
  7.     label2->setString(time_str);  
  8.   
  9. }  

0 0
原创粉丝点击