我无法使用原生cocos2d-x功能下载图片。 我正在使用HttpRequest尝试在Android上下载图片。 当我在Java中使用URL,InputStream和OutputStream来下载图片。 当我尝试使用原生cocos2d-x函数时,图片是有效的。图片有问题。 有问题的Cocos2d-x版本是写作时的最新版本3.0。
答案 0 :(得分:3)
在cocos2d-x中编写此代码
void HelloWorld::loadImage()
{
log("onHttpRequestCompleted In the request");
HttpRequest* request = new (std::nothrow) HttpRequest();
request->setUrl("https://graph.facebook.com/100000706355105/picture?width=120&height=120");
request->setRequestType(cocos2d::network::HttpRequest::Type::GET);
request->setResponseCallback(CC_CALLBACK_2(HelloWorld::onRequestImgCompleted, this));
request->setTag("Post test2");
HttpClient::getInstance()->send(request);
request->release();
}
在RequestCompleted上
void HelloWorld::onRequestImgCompleted(HttpClient *sender, HttpResponse *response)
{
log("In HelloWorld");
log("AppDelegate::onHttpRequestCompleted - onHttpRequestCompleted BEGIN");
if (!response)
{
log("onHttpRequestCompleted - No Response");
return;
}
log("onHttpRequestCompleted - Response code: %lu", response->getResponseCode());
if (!response->isSucceed())
{
log("onHttpRequestCompleted - Response failed");
log("onHttpRequestCompleted - Error buffer: %s", response->getErrorBuffer());
return;
}
log("onHttpRequestCompleted - Response code: %s", response->getResponseDataString());
std::vector<char> *buffer = response->getResponseData();
const char* file_char = buffer->data();
log("onHttpRequestCompleted - Response code: %s", file_char);
Image * image = new Image ();
image-> initWithImageData ( reinterpret_cast<const unsigned char*>(&(buffer->front())), buffer->size());
Texture2D * texture = new Texture2D ();
texture-> initWithImage (image);
Sprite * sprite = Sprite :: createWithTexture (texture);
sprite->setPosition(Vec2(visibleSize.width/2, visibleSize.height / 2));
addChild(sprite);
log("onHttpRequestCompleted height %f", sprite->getContentSize().height);
}