触摸开始时更改菜单项目标签颜色



嘿,我在任何地方都找不到答案。我想在触摸时更改菜单ItemLabel的字体颜色。默认情况下,当你第一次触摸它时,它会缩放并设置更大的动画,但如何更多地自定义它?这是我的标签和菜单项:

//add options label
optionsLabelSettings = Label::createWithTTF("OPTIONS", "fonts/font1.ttf", 140);
optionsLabelSettings->setColor(Color3B(255,255,255));
auto optionsItem = MenuItemLabel::create(optionsLabelSettings, CC_CALLBACK_1(MainMenuScene::GoToOptionsScene, this));
optionsItem->setPosition( Point (visibleSize.width/2  + origin.x, visibleSize.height /2));
//add menu
auto menu = Menu::create(optionsItem, NULL);
menu->setPosition( Point(0,0));
this->addChild(menu);

如果您想更改字体颜色,可以在处理程序中插入这样的方法:

void MainMenuScene::GoToOptionsScene(parameters)
{
optionsItem->getLabel()->setColor(Color3B::BLACK); // or any other color
… // your method of switching to another scene
}

如果按下后切换到另一个场景,则可以。
但是如果你打算停留在当前的场景中,这种方法是不合适的,因为你无法恢复字体的颜色。在这种情况下,更好的方法是使用MenuItemImage并为正常状态和选定状态创建图像:

MenuItemImage *optionsItem = MenuItemImage::create(«normalImage.png», «selectedImage.png», CC_CALLBACK_1(MainMenuScene::GoToOptionsScene, this));

或者使用ui::按钮,如果你没有图像:

ui::Button* optionsItem = ui::Button::create();
    optionsItem->setPosition(…);
    optionsItem->setTitleText(«OPTIONS»);
    optionsItem->setTitleFontName("fonts/font1.ttf");
    optionsItem->setTitleFontSize(140);
    optionsItem->setTitleColor(Color3B::WHITE);
    optionsItem->addTouchEventListener([&](Ref* sender, Widget::TouchEventType type){
        switch (type)
        {
            case ui::Widget::TouchEventType::BEGAN:
                this->startPressingGoToOptionsScene();
                break;
            case ui::Widget::TouchEventType::ENDED:
                this->finishPressingGoToOptionsScene();
                break;
            default:
                break;
        }
    });
    this->addChild(optionsItem);

然后在每个处理程序中设置不同的按钮行为:

void MainMenuScene::startPressingGoToOptionsScene(parameters)
{
optionsItem->setTitleColor(Color3B::BLACK);
optionsItem->setTitleText(«…») // change anything else
…
}
void MainMenuScene::finishPressingGoToOptionsScene(parameters)
{
optionsItem->setTitleColor(Color3B::WHITE); // return original font color and other changes
…
}
customise your MenuItemLabel class & Implement following two methods  :-
class ChangedMenuItemLabel : MenuItemLabel
{
bool ChangedMenuItemLabel::initWithLabel(cocos2d::Node *label, const ccMenuCallback &callback)
{
    if (!MenuItemLabel::initWithLabel(label,callback)) {
        return false;
    }
    return true;
}
void selected(){
this->setColor("your color");
}
void unselected(){
this->setColor("your color");//or nothing
}
}

最新更新