Change Font Colour In The Same Text

Hi everyone,

I wrote a code for dialogues:

label = CCLabelBMFontAnimated::createWithTTF("", "fonts/PressStart2P.ttf", 20.0f,
	Size(visibleSize.width, 40),
	cocos2d::TextHAlignment::CENTER, cocos2d::TextVAlignment::CENTER);
label->setTextColor(Color4B::BLACK);

label->setString("WE_HAVE_DOZENS_OF_PAPERWORK!!!");

I need to change “_” character’s colour to white. Is it possible ?

I think you can create a separate label for _ and concatenate them together in setString

you can get individual letter like this

Sprite *letterSprite = label->getLetter(2); // this would return the first “_”

so you could do something like this

std::string str = label->getString();
    
    for(int i = 0 ; i < str.length() ; i ++)
    {
        if(str.at(i) == '_')
        {
           label->getLetter(i)->setColor(Color3B::White);
        }
        else{
            if(label->getLetter(i) != nullptr)
            {
                label->getLetter(i)->setColor(Color3B::Black);

            }
        }
    }
2 Likes

This is a good solution too. Thanks @bilalmirza for mentioning it.

It Worked perfectly. Thank you soo much :slight_smile:

Let us know how performance is. Substringing a lot of labels frequently may cause some performance issues. I’m not sure I’m just saying.

Obviously I did not experience any performance loss. I added animations to my dialogue system. This code made the animation work properly. Although more than twenty dialog texts were opened at the same time, there was no loss of performance.

2 Likes

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.