下面我们就来详细的说下关于cocos2dx 菜单按钮,下面我会贴出详细的代码来供大家参考和学习,有些不对的地方大家可以在社区里面留言,我会做一个详细的解答。
1,在没有图片资源的情况下,如果想要创建一个只有字体的Menu按钮,看如下代码的创建步骤:
-
CCLabelTTF *label = CCLabelTTF::create("Exit", "Arial", 20); // create a exit botton
-
CCMenuItemLabel *exit_game = CCMenuItemLabel::create(label, this, menu_selector(HelloWorld::menuExitGame) );
-
exit_game->setPosition(CCPointZero);
-
exit_game->setPosition(size.width -40, size.height - 40); // add an exit button
-
CCMenu* pMenu = CCMenu::create( exit_game,NULL); //最后添加进去,就创建成功了
2,我需要用图片资源来创建自己风格的Menu菜单,代码如下:
-
CCMenuItemImage *pCloseItem = CCMenuItemImage::create(
-
"NextLayeNormal.png", //png.jpg等图片格式都是可以的
-
"NextLayeSelected.png",
-
this,
-
menu_selector(HelloWorld::menuCallback));
-
CC_BREAK_IF(! pCloseItem);
-
pCloseItem->setPosition(ccp(CCDirector::sharedDirector()->getWinSize().width - 70, 30));
-
-
CCMenu* pMenu = CCMenu::create( <span style="font-family: Arial, Helvetica, sans-serif;">pCloseItem </span>,NULL); //最后添加进去,就创建成功了
-
以上是两种创建menu菜单的方式,还有另外几种方式,CCLabelAtlas,CCMenuItemFont
-
[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
-
CCLabelAtlas *plabelAtals = CCLabelAtlas::create("0123456789", "labelatlas.png", 16, 24, '.');
-
plabelAtals->setColor(ccc3(250, 100, 0));
-
CCMenuItemLabel *atalsMenu = CCMenuItemLabel::create(plabelAtals, this, menu_selector(MenuDemo::font_callBack));
-
atalsMenu->setPosition(ccp(size.width / 3, size.height / 2));
-
CCMenu *menu = CCMenu::create(atalsMenu, NULL);
-
menu->setPosition(CCPointZero);
-
-
-
CCMenuItemFont::setFontName("Marker Felt");
-
CCMenuItemFont *menufont = CCMenuItemFont::create("My test Menu", this, menu_selector(MenuDemo::menuCallbackPriorityTest));
-
menufont->setColor(ccc3(250, 100, 0));
-
menufont->setPosition(ccp(size.width - 200, size.height / 2));
-
menu->setPosition(CCPointZero);
-
menu->addChild(menufont, 1);
-
-
this->addChild(menu, 1);
采用CCMenuItemToggle来创建开关菜单,例子代码如下:
-
void MyMenuItemToggleLayer::initLayer() {
-
CCSize size = CCDirector::sharedDirector()->getWinSize();
-
CCSprite *bg = CCSprite::create("BG.jpg");
-
bg->setPosition(ccp(size.width / 2.0f, size.height / 2.0f));
-
this->addChild(bg, 1);
-
CCMenuItemFont::setFontName( "Marker Felt" );
-
CCMenuItemFont::setFontSize(34);
-
CCMenuItemFont *on = CCMenuItemFont::create("On", this, menu_selector(MyMenuItemToggleLayer::onCallBack));
-
on->setPosition(ccp(400, 400));
-
CCMenuItemFont *create = CCMenuItemFont::create("Create", this, menu_selector(MyMenuItemToggleLayer::createCallBack));
-
create->setPosition(ccp(500, 500));
-
CCMenuItemToggle *toggle = CCMenuItemToggle::create( this,
-
menu_selector(MyMenuItemToggleLayer::CallBack),
-
on,
-
create,
-
NULL);
-
toggle->setColor(ccc3(255, 0 ,0));
-
toggle->setPosition(ccp(size.width / 2.0f, size.height / 2.0f));
-
CCMenu *menu = CCMenu::create(toggle, NULL);
-
menu->setPosition(CCPointZero);
-
this->addChild(menu, 2);
-
-
}