Is it possible to use remote images in ccui.ImageView?

Can you share what changes you made to get RemoteSprite to compile in c++? The code isn’t correct and I don’t see how to fix it at first glance? I will dig into it further, but if you don’t mind sharing your correct code for the callback/downloadFailed, that’d be great?

I didn’t implemented the code with a fail retry count. But I think it is not a very difficult task.
Because I am using the cocos2d-js and I don’t know much about how to bind a new class to javascript. Therefore, I just modify the CCSprite class to make it work. It is a bit dirty, but it works.

I didn’t created a RemoteSprite class, but just checked if the input string is begin will http in the initWithFile method. If yes,
_url = filename;
downloadImage();
return initWithFile(“res/cantload.png”);
if no, keep the old flow.

void Sprite::downloadImage(void)
{
network::HttpClient *client = network::HttpClient::getInstance();
network::HttpRequest *request = new network::HttpRequest();

request->setUrl(_url.c_str());
request->setRequestType(network::HttpRequest::Type::GET);
request->setResponseCallback([=](network::HttpClient* client, network::HttpResponse* response)
{
    try {
        if (response->isSucceed() || response->getResponseCode () != 200) {
            auto buffer = response->getResponseData();
    
            cocos2d::Image * img = new cocos2d::Image;
            img->initWithImageData(reinterpret_cast<unsigned char*>(&(buffer->front())), buffer->size());
    
            auto textureCache = cocos2d::Director::getInstance()->getTextureCache();

            auto previousTexture = textureCache->getTextureForKey(_url);
            if (previousTexture)
            {
                textureCache->removeTextureForKey(_url);
            }
    
            cocos2d::Texture2D* texture = textureCache->addImage(img, _url);
    
            img->release();
    
            _texture = texture;
        }
    } catch (exception& e) {
    }
});
client->send(request);
request->release();

}

1 Like

Hi, I guess your code got truncated or something. It’s not completed.