这是自己做项目时遇到的,这部分代码是自己在 前辈们的基础上自己在增加了少许代码,让代码更比较完整一些,亲测可用,方便实惠。不多说,上代码,感谢网上的前辈
CImageDownload.h
class CImageDownloader : public cocos2d::CCObject
{
public:
virtual bool init();
void SendHttpRequest(CCObject* pTarget, SEL_ImageNotification pSelector, const char* url, CCNode* node, const char* filename);
void HttpRequestComplete(cocos2d::extension::CCHttpClient *sender, cocos2d::extension::CCHttpResponse *response);
CREATE_FUNC(CImageDownloader);
public:
//观察者ID
CCString observerID;
//下载的图片加载到当前layer层上
CCNode* node;
//是否使用遮罩
bool useMask;
//图片文件名
const char* filename;
};
CImageDownload.cpp
bool CImageDownloader::init()
{
useMask = false;
return true;
}
void CImageDownloader::SendHttpRequest(CCObject* pTarget, SEL_ImageNotification pSelector, const char* url, CCNode* node, const char* filename)
{
std::string path = CCFileUtils::sharedFileUtils()->getWritablePath();
path += filename;
if (CCFileUtils::sharedFileUtils()->isFileExist(CCFileUtils::sharedFileUtils()->fullPathForFilename(path.c_str())))
{
CCSprite* spr = CCSprite::create(path.c_str());
node->addChild(spr);
return;
}
CCHttpRequest* request = new CCHttpRequest();
this->node = node;
this->filename = filename;
if (this->node)
{
this->observerID = CCImageNotificationCenter::sharedImageNotificationCenter()->addObserver(filename,node,useMask);
}
request->setUrl(url);
request->setRequestType(CCHttpRequest::kHttpGet);
request->setResponseCallback(this, httpresponse_selector(CImageDownloader::HttpRequestComplete));
CCImageNotificationCenter::sharedImageNotificationCenter()->m_ImageNotificationTarget = pTarget;