Changing a button's image

Changing a button's image

Say I have a button which is displaying “1.png”.
I now change “1.png” using FileUtils::getInstance()->writeStringToFile() and want the button’s image to change to the new “1.png”. I’ve tried using btn->loadTextureNormal(“1.png”) but it doesn’t work for me.
Is there a proper way to do this? Or do I have to delete the old button and create a new one?


well, what class type is your button?

A Sprite or a ui::button?

In cocos2d-x, files with the same path are cached,
Even if you change the contents of the file, the display does not change as it is.
You need to clear the cache.

void clearTextureCache(string path) {
   auto cache = Director::getInstance()->getTextureCache();


I’ve never cleared the cache when changing textures unless the file name is the same name and for me it never is.

My button is ui::Button

got it. The API Ref has what you need:

and cpp-tests has a working example of doing this.

From my understanding, the test is using btn->loadTextureNormal() which is what I have tried. However, it only sometimes works. I have tried clearing the cache like @bluewind00 has suggested but it still only sometimes works. Also, the filename is the same name, before and after.

what about creating a button and setting the way it looks from a Sprite then change the texture of the Sprite as needed?

Sprite *sprite = Sprite::create("cocosui/animationbuttonnormal.png");

It works for me.

Button *btn = Button::create();
btn->addTouchEventListener([=](Ref* sender, Widget::TouchEventType type) {
        //if you want to change the button image when you touch the button, is better to make a separate method instead of this one, and use loadTextureNormal, changing this property in the already added button

If you want to change the button’s image, you should have 2 different images/filenames (the original, and the new one)

I just tried it again and it now works. It seems that I had something elsewhere that was preventing the images from updating properly.

I don’t need to clear the cache.
The filename can be the same before and after.
I used btn->loadTextureNormal("filename") where btn is a ui::Button.

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