Cocos2d-x之CCMenu理解
Menu创建菜单:
Cocos2d-x下的菜单创建包括:
1.CCMenuItemFont 字体按钮创建
CCMenuItemFont * onlineVideo = MenuItemFont::create("Play online video", CC_CALLBACK_1(HelloWorld::menuOnlineVideoCallback, this));其中CC_CALLBACK_1代表其括号体里面为一回调函数,1代表参数个数;
onlineVideo->MenuItemFont::setFontSize(20);表示字体的大小;
2.CCMenuItemImage 图片按钮创建
顾名思义,按钮以图片的形式存在,点击后进入回调函数响应。
auto closeItem = MenuItemImage::create("CloseNormal.png","CloseSelected.png",CC_CALLBACK_1(HelloWorld::menuCloseCallback, this));
closeItem->setPosition(Vec2(origin.x + visibleSize.width - closeItem->getContentSize().width/2 ,origin.y + closeItem->getContentSize().height/2));
3.CCMenuItemToggle 开关按钮创建
1 CCMenuItemToggle* itemWithTarget(CCObject* target, SEL_MenuHandler selector, CCMenuItem* item, ...); 2 CCMenuItemToggle* item1 = CCMenuItemToggle::itemWithTarget(this,menu_selector(MenuLayer4::menuCallback), 3 CCMenuItemFont::itemFromString( "On" ), 4 CCMenuItemFont::itemFromString( "Off"),NULL );
CCMenu:
auto menu = Menu::create(closeItem,NULL);其实create内的参数可以为n个参数,NULL参数表示截至的参数,如此一来,当有n个参数时,不必每次都调用menu->addchild(item),可以方便的写成以下形式: auto closeItem = MenuItemImage::create("CloseNormal.png","CloseSelected.png",CC_CALLBACK_1(HelloWorld::menuCloseCallback, this)); auto resourceVideo = MenuItemFont::create("Play resource video", CC_CALLBACK_1(HelloWorld::menuResourceVideoCallback, this)); auto onlineVideo = MenuItemFont::create("Play online video", CC_CALLBACK_1(HelloWorld::menuOnlineVideoCallback, this)); auto ratioSwitch = MenuItemFont::create("KeepRatioSwitch", CC_CALLBACK_1(HelloWorld::menuRatioCallback, this)); auto fullSwitch = MenuItemFont::create("FullScreenSwitch", CC_CALLBACK_1(HelloWorld::menuFullScreenCallback, this)); auto menu = Menu::create(resourceVideo,onlineVideo,ratioSwitch,closeItem,fullSwitch,NULL); menu->alignItemsVerticallyWithPadding(30);此句话的意思是Menu下的内容垂直对齐,30对应与间隔;
下面举个例子来说明上述菜单中回调函数的应用:
1 void HelloWorld::menuResourceVideoCallback(Ref* pSender) 2 { 3 if (_videoPlayer) 4 { 5 sprite->setOpacity(0); 6 _videoPlayer->setFileName("v.mp4"); 7 _videoPlayer->play(); 8 } 9 }
点击Menu中的playRecource菜单按钮后,执行此函数,播放本地视频。