文本菜单类MenuItemFont,它的其中一个建立函数create定义以下:html
[html] view plaincopy数组
static MenultemAtlasFont*create ( const std::string & value, //要显示的文本 函数
const ccMenuCallback & callback //菜单操做的回调函数指针 字体
) this
文本菜单类MenuItemAtlasFont是基于图片集的文本菜单项,它的其中一个建立函数create定义以下:spa
[html] view plaincopy.net
static MenuItemAtlasFont* create ( const std::string & value, //要显示的文本 指针
const std::string & charMapFile, //图片集合文件 code
int itemWidth, //要截取的文字在图片中的宽度 orm
int itemHeight, //要截取的文字在图片中的高度
char startCharMap //菜单操做的回调函数指针
)
此次咱们会经过一个实例介绍一下文本菜单的使用,这个实例以下图所示,其中菜单Start是使用MenuItemFont实现的,菜单Help是使用MenuItemAtlasFont实现的。
下面咱们看看HelloWorldScene.cpp中init函数以下:
[html] view plaincopy
bool HelloWorld::init()
{
if ( !Layer::init() )
{
return false;
}
Size visibleSize = Director::getInstance()->getVisibleSize();
Point origin = Director::getInstance()->getVisibleOrigin();
Sprite *bg =Sprite::create("menu/background.png");
bg->setPosition(Point(origin.x + visibleSize.width/2,
origin.y +visibleSize.height /2));
this->addChild(bg);
MenuItemFont::setFontName("Times New Roman"); ①
MenuItemFont::setFontSize(86); ②
MenuItemFont *item1 = MenuItemFont::create("Start",
CC_CALLBACK_1(HelloWorld::menuItem1Callback,this)); ③
MenuItemAtlasFont *item2 = MenuItemAtlasFont::create("Help",
"menu/tuffy_bold_italic-charmap.png",48, 65, ' ',
CC_CALLBACK_1(HelloWorld::menuItem2Callback,this)); ④
Menu* mn = Menu::create(item1, item2, NULL); ⑤
mn->alignItemsVertically(); ⑥
this->addChild(mn); ⑦
return true;
}
上述代码第①和②行是设置文本菜单的文本字体和字体大小。第③行代码是建立MenuItemFont菜单项对象,它是一个通常文本菜单,create是函数的第一个参数是菜单项的文本内容,第二个参数是点击菜单项回调的函数指针。其中CC_CALLBACK_1宏是定义一个回调函数,并函数与对象绑定在一块儿,1表示这个函数有一个输出参数,HelloWorld::menuItem1Callback是函数指针,this表明函数所在的对象。
HelloWorld::menuItem1Callback须要在HelloWorld.h头文件中声明,HelloWorld.h头文件代码以下:
[html] view plaincopy
#include "cocos2d.h"
class HelloWorld : public cocos2d::Layer
{
public:
virtual bool init();
static cocos2d::Scene* scene();
void menuItem1Callback(cocos2d::Ref*pSender);
void menuItem2Callback(cocos2d::Ref*pSender);
CREATE_FUNC(HelloWorld);
};
回调函数代码以下,函数中的参数是菜单项MenuItem的实例。
[html] view plaincopy
void HelloWorld::menuItem1Callback(Ref*pSender)
{
MenuItem* item = (MenuItem*)pSender;
log("TouchStart Menu Item %p", item);
}
void HelloWorld::menuItem2Callback(Ref*pSender)
{
MenuItem* item = (MenuItem*)pSender;
log("TouchHelp Menu Item %p", item);
}
HelloWorldScene.cpp中init函数中第④行代码是建立一个MenuItemAtlasFont菜单项对象,这种菜单项是基于图片集的菜单项。MenuItemAtlasFont须要将图片集放到资源目录Resources下。在本例中咱们是将全部的图片都放到一个Resources下的menu目录中,因此create函数的第二个参数是"menu/tuffy_bold_italic-charmap.png",要求带有menu路径。
还有第⑤行代码Menu* mn = Menu::create(item1, NULL)是建立菜单对象,把以前建立的菜单项添加到菜单中,create函数中有是这些菜单项的数组,最后要用NULL结束。第⑥行代码mn->alignItemsVertically()是设置菜单项垂直对齐。第⑦行代码是this->addChild(mn,1,2)是把菜单对象添加到当前层中。