这次准备做一些网络的功能,账号注册登录的功能已经完成了,现在需要完成玩家头像的功能,首先是获取网络图片。
为此在网上看了很多博客和文章,终于尝试成功了,原帖在http://www.cnblogs.com/leehongee/p/4038311.html
但是现在只完成了在win32上获取图片,还没有尝试android平台,下次尝试获取联网权限。
在.h里包含头文件
#include "network/HttpClient.h" using namespace cocos2d::network;
并在类中声明
void doHttpRequest(const char* url,const char* tag,const ccHttpRequestCallback& callback); void onHttpRequestImageCompleted(HttpClient *sender,HttpResponse *response); //获取请求网络图片资源 cocos2d::Texture2D* texture;
在.cpp添加
void HelloWorld::doHttpRequest(const char* url,const ccHttpRequestCallback& callback) { HttpRequest* request = new HttpRequest(); request->setUrl(url); request->setRequestType(HttpRequest::Type::POST); //这是回调对象和回调函数 request->setResponseCallback(callback); request->setTag(tag); HttpClient::getInstance()->send(request); //释放内存 request->release(); } void HelloWorld::onHttpRequestImageCompleted(HttpClient *sender,HttpResponse *response) { if (!response) { return; } // You can get original request type from: response->request->reqType const char* tag = response->getHttpRequest()->getTag(); if (0 != strlen(tag)) { log("%s completed",response->getHttpRequest()->getTag()); } if (!response->isSucceed()) { log("error buffer: %s",response->getErrorBuffer()); return; } std::vector<char> *buffer = response->getResponseData(); //create image Image* image = new Image; image->initWithImageData((unsigned char*)buffer->data(),buffer->size()); //create texture texture = new Texture2D(); bool isImage = texture->initWithImage(image); if(isImage){ log("Texture2D init success"); } image->release(); }
以上是已经写好的函数,可以直接拿来用,现在我们需要知道怎么使用它:
doHttpRequest("http://127.0.0.1/pic/default.jpg","pic",CC_CALLBACK_2(HelloWorld::onHttpRequestImageCompleted,this));我读取了本地服务器的一张图片 原文链接:https://www.f2er.com/cocos2dx/342152.html