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?

Thanks

well, what class type is your button?

A Sprite or a ui::button?

https://docs.cocos2d-x.org/api-ref/cplusplus/v4x/d3/d5c/classcocos2d_1_1_sprite.html#a2d5e5b2268888fdd00887fed0944cac5

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();
   cache->removeTextureForKey(path);
}

clearTextureCache("1.png");

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: https://docs.cocos2d-x.org/api-ref/cplusplus/v4x/d2/db1/classcocos2d_1_1ui_1_1_button.html#adf271b1be4c753b7f9ddf23e8f67c530

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");
button2->addChild(sprite);

It works for me.

Button *btn = Button::create();
btn->loadTextureNormal(imagePath);
btn->setPosition(position);
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
        .
    });
this->addChild(btn);

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.

Note:
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.