Cocos2dx使用网络图片

时间:2022-11-21 20:38:03

#ifndef __Demo__Connection__

#define __Demo__Connection__

#include <iostream>

#include "cocos2d.h"

#include "network/HttpClient.h"

USING_NS_CC;

using namespace std;

using namespace cocos2d::network;

class Connection {

public:

  void doHttpRequest(const char* url, const char* requestData, const char* tag, const ccHttpRequestCallback& callback);

  void onHttpRequestImageCompleted(HttpClient *sender, HttpResponse *response);

private:

  //获取请求网络图片资源

  Texture2D* m_pTexture;

};

#endif /* defined__Demo__Connection__*/

#include "Connection.h"/** 编译到Android平台之后注意添加联网权限 **/

void Connection::doHttpRequest(const char* url, const char* requestData, const char* tag, const ccHttpRequestCallback& callback) {

  HttpRequest* request = new HttpRequest();

  request->setUrl(url);

  request->setRequestType(HttpRequest::Type::POST);               //这是回调对象和回调函数

  request->setResponseCallback(callback); request->setTag(tag);     //请求的数据

  if (strlen(requestData) != 0){

    request->setRequestData(requestData, strlen(requestData));

  }

  HttpClient::getInstance()->send(request); //释放内存

  request->release();

}

void Connection::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;

  }

  auto buffer = response->getResponseData();  //create image

  auto image = new Image;

  if (image->initWithImageData((unsigned char*)buffer->data(), buffer->size()))  {

    auto texture = new Texture2D();

    if (texture->initWithImage(image))   {

        //直接使用该纹理创建

      m_pTexture = texture;

      CCLOG("TextTure2D Init Start");

      auto sprite = Sprite::createWithTexture(texture);

      sprite->setPosition(getContentSize() / 2);

      addChild(sprite);

      CCLOG("TextTure2D Init Finished ");

     //把该图片保存到本地

      std::string backData = " ";

      backData.append(buffer->begin(), buffer->end());

      std::string strSavePath = FileUtils::getInstance()->getWritablePath() + StringUtils::format("NetPhoto.png");

      FILE *fp = fopen(strSavePath.c_str(), "wb+");

      fwrite(backData.c_str(), 1, backData.size(), fp);

      fclose(fp);

    }

    texture->release();

   }

  image->release();

}