20
20

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

cocos2d-xでダウンロードした画像をファイルに保存せず表示する

Last updated at Posted at 2015-01-22
  1. 普通にHTTP通信で画像のデータを取ってくる
  2. データからcocos2d::Image作る
  3. cocos2d::TextureCacheに渡してキャッシュ&cocos2d::Texture2D取得する
  4. cocos2d::Sprite::createWithTextureでSprite作る
  5. 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);
20
20
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
20
20

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?