菜單是我們在開發(fā)中經(jīng)常用到的元素,cocos2d-x中的菜單基本上是分裝了文本類和精靈類,代碼注釋有詳細(xì)的說明,看代碼吧!


bool HelloWorld::init(){ bool bRet = false; do { CC_BREAK_IF(! CCLayer::init()); CCLabelTTF * ttf = CCLabelTTF::create("cocos2d","Arial",24); //沒有設(shè)置坐標(biāo),默認(rèn)放到CCMenu層的中間,第二個參數(shù)是事件處理函數(shù)屬于的類,第三個參數(shù)就是調(diào)用的函數(shù) //menu_selector菜單選擇器 CCMenuItemLabel * labelMenu = CCMenuItemLabel::create(ttf,this,menu_selector(HelloWorld::show)); //可以提前修改字體和大小,否則使用默認(rèn)的 CCMenuItemFont::setFontName("Arial"); CCMenuItemFont::setFontSize(50); //內(nèi)部實(shí)現(xiàn)是創(chuàng)建出一個CCLabelTTF,然后用CCLabelTTF創(chuàng)建CCMenuItemLabel CCMenuItemFont * fontMenu = CCMenuItemFont::create("cocos2d",this,menu_selector(HelloWorld::show)); //內(nèi)部實(shí)現(xiàn)是創(chuàng)建出一個CCLabelAtlas,然后用CCLabelAtlas創(chuàng)建CCMenuItemLabel CCMenuItemAtlasFont * atlasMenu = CCMenuItemAtlasFont::create("2014/2/12","fps_images.png", 12,32,'.',this,menu_selector(HelloWorld::show)); //內(nèi)部實(shí)現(xiàn)是創(chuàng)建一個CCSprite,用CCSprite創(chuàng)建CCMenuItemSprite CCMenuItemImage * imgMenu = CCMenuItemImage::create("CloseNormal.png","CloseSelected.png",this, menu_selector(HelloWorld::show)); CCMenuItemFont * font1 = CCMenuItemFont::create("start"); CCMenuItemFont * font2 = CCMenuItemFont::create("stop"); CCMenuItemToggle * toggle = CCMenuItemToggle::createWithTarget(this,menu_selector(HelloWorld::show2), font1,font2,NULL); //CCMenu就是一個特殊的CCLayer,只是這個層中只能放CCMenuItem和CCMenuItem的子類 //在這個層中,可以為CCMenuItem進(jìn)行布局,因?yàn)槭菍铀宰鴺?biāo)當(dāng)然默認(rèn)是(0,0),而且是以左下角點(diǎn)占據(jù)坐標(biāo)位置的 CCMenu * menu = CCMenu::create(labelMenu,fontMenu,imgMenu,toggle,NULL); //為菜單項(xiàng)進(jìn)行布局,否則就疊加在一起了 menu->alignItemsHorizontallyWithPadding(10); this->addChild(menu); bRet = true; } while (0); return bRet;}事件激活函數(shù)如下,不要忘記在頭文件中聲明一下。
void HelloWorld::show(CCObject * pSender){ CCLog("label menu!");}void HelloWorld::show2(CCObject * sender){ CCMenuItemToggle * toggle = (CCMenuItemToggle*)sender; if(toggle->getSelectedIndex() == 0) { CCLog("start"); } else if(toggle->getSelectedIndex() == 1) { CCLog("stop"); }}新聞熱點(diǎn)
疑難解答
圖片精選