- 普通にHTTP通信で画像のデータを取ってくる
- データから
cocos2d::Image
作る -
cocos2d::TextureCache
に渡してキャッシュ&cocos2d::Texture2D
取得する -
cocos2d::Sprite::createWithTexture
でSprite作る -
addChild
で表示する
以降はcocos2d::Director::getInstance()->getTextureCache()->getTextureForKey(url)
でテクスチャ取得できるはず。
ui::ImageView
の場合は、SpriteFrameCacheに登録すれば以降ImageView::create(spriteFrameName, cocos2d::ui::TextureResType::PLIST);
という感じで作れる。
auto url = "任意の画像のURL";
auto request = new cocos2d::network::HttpRequest();
request->setUrl(url);
request->setRequestType(cocos2d::network::HttpRequest::Type::GET);
request->setResponseCallback([this, url](cocos2d::network::HttpClient *, cocos2d::network::HttpResponse *response) {
if (!response->isSucceed()) {return;}
auto responseData = response->getResponseData();
auto bytes = reinterpret_cast<unsigned char *>(&(responseData->front()));
auto data = cocos2d::Data();
data.copy(&(bytes.front()), bytes.size());
auto image = new (std::nothrow) cocos2d::Image();
if (!image) {return;}
image->initWithImageData(data.getBytes(), data.getSize());
auto texture = cocos2d::Director::getInstance()->getTextureCache()->addImage(image, url);
auto spriteFrame = cocos2d::SpriteFrame::createWithTexture(texture, cocos2d::Rect(0, 0, texture->getContentSize().width, texture->getContentSize().height));
cocos2d::SpriteFrameCache::getInstance()->addSpriteFrame(spriteFrame, url);
CC_SAFE_RELEASE(image);
auto sprite = cocos2d::Sprite::createWithTexture(texture);
this->addChild(sprite);
// or
auto imageView = cocos2d::ui::ImageView::create(url, cocos2d::ui::TextureResType::PLIST);
this->addChild(imageView);
});
cocos2d::network::HttpClient::getInstance()->send(request);