Search code examples
iosiphonecocos2d-xgame-engine

Cocos2d-x how to create image button with title and font


Hi i am converting my game from Corona SDK to Cocos2d-x 3.0 alpha.

I need to create an image button with text on it. It was very simple in Corona SDK with widget.newButton, which takes all x, y, size, font, image etc in single function.

Now i couldn't find any alternate to this in Cocos2d-x. The closest thing i have found in it is MenuItemImage

auto closeItem = MenuItemImage::create(
                                    "blank.png",
                                    "blank-selected.png",
                                     CC_CALLBACK_1(HelloWorld::menuCloseCallback, this));

closeItem->setPosition(Point(origin.x + visibleSize.width - closeItem->getContentSize().width/2 , origin.y + closeItem->getContentSize().height/2));

auto menu = Menu::create(closeItem, NULL);
menu->setPosition(Point::ZERO);
this->addChild(menu, 1);

It takes the images and event, but i cannot set title and font on it. Anyone has idea how to set title and font on it?


Solution

  • You can use MenuItemFont or MenuItemLabel.

    For example:

    MenuItemFont::setFontName( "Marker Felt" );
    MenuItemFont::setFontSize( 34 );
    
    auto label = LabelBMFont::create( "go back", "fonts/bitmapFontTest3.fnt" );
    auto back = MenuItemLabel::create(label, CC_CALLBACK_1(MenuLayer4::backCallback, this) );
    

    or

    MenuItemFont::setFontSize( 34 );
    MenuItemFont::setFontName("Marker Felt");
    auto item6 = MenuItemFont::create("Bugs", CC_CALLBACK_1(MenuLayerMainMenu::menuCallbackBugsTest, this));
    

    For more information, see MenuTest.ccp


    update

    You can simply new a Label, and add it to you MenuItemImage, such as:

    LabelTTF* closeLabel = LabelTTF::create("close", "Marker Felt", 28);
    closeItem->addChild(closeLabel);
    

    And you may need to adjust the label's position.