文本菜單類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)是把菜單對象添加到當前層中。