Last active
January 1, 2016 08:59
-
-
Save gin0606/8122264 to your computer and use it in GitHub Desktop.
Cocos2d-xで画像のダウンロードと保存。保存した画像をCCSpriteで表示する
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// HTTP通信 | |
void ResourceDownloader::startDownload(char const *url) { | |
CCHttpRequest *request = new CCHttpRequest(); | |
request->setUrl(url); | |
request->setRequestType(cocos2d::extension::CCHttpRequest::kHttpGet); | |
request->setResponseCallback(this, httpresponse_selector(ResourceDownloader::onHttpRequestCompleted)); | |
CCHttpClient::getInstance()->send(request); | |
request->release(); | |
} | |
// コールバックメソッドの中で受信したファイルを保存する | |
void ResourceDownloader::onHttpRequestCompleted(CCHttpClient *client, CCHttpResponse *response) { | |
if (!response->isSucceed()) {return;} | |
std::string filePath = CCFileUtils::sharedFileUtils()->getWritablePath() + "image.png"; | |
std::vector<char> *buffer = response->getResponseData(); | |
std::ofstream ofs; | |
ofs.open(filePath.c_str(), std::ios::out | std::ios::trunc); | |
ofs.write(&(buffer->front()), buffer->size()); | |
ofs.flush(); | |
ofs.close(); | |
} | |
// 保存した画像を使う | |
void ResourceDownloader::createSprite() { | |
std::string filePath = CCFileUtils::sharedFileUtils()->getWritablePath() + "image.png"; | |
CCSprite sprite = CCSprite::create(filePath); | |
sprite->setPosition(ccp(320, 240)); | |
CCNode *pObject = dynamic_cast<CCNode *>(CCDirector::sharedDirector()->getRunningScene()->getChildren()->objectAtIndex(0)); | |
pObject->addChild(sprite); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment