cocos2d-x 网络下载图片

19 篇文章 0 订阅
2 篇文章 0 订阅

转自 http://blog.csdn.net/tj_slamdunk/article/details/12016853

这是自己做项目时遇到的,这部分代码是自己在 前辈们的基础上自己在增加了少许代码,让代码更比较完整一些,亲测可用,方便实惠。不多说,上代码,感谢网上的前辈

  1. CImageDownload.h  
  2.   
  3. class CImageDownloader : public cocos2d::CCObject  
  4. {  
  5.       
  6. public:  
  7.   
  8.     virtual bool init();  
  9.   
  10.     void SendHttpRequest(CCObject* pTarget, SEL_ImageNotification pSelector, const char* url, CCNode* node, const char* filename);  
  11.     void HttpRequestComplete(cocos2d::extension::CCHttpClient *sender, cocos2d::extension::CCHttpResponse *response);  
  12.   
  13.     CREATE_FUNC(CImageDownloader);  
  14. public:  
  15.     //观察者ID  
  16.     CCString    observerID;  
  17.     //下载的图片加载到当前layer层上  
  18.     CCNode*    node;  
  19.     //是否使用遮罩  
  20.     bool        useMask;  
  21.     //图片文件名  
  22.     const char* filename;  
  23. };  

  1. CImageDownload.cpp  
  2.   
  3. bool CImageDownloader::init()  
  4. {  
  5.     useMask = false;  
  6.     return true;  
  7. }  
  8.   
  9. void CImageDownloader::SendHttpRequest(CCObject* pTarget, SEL_ImageNotification pSelector, const char* url, CCNode* node, const char* filename)  
  10. {  
  11.     std::string path = CCFileUtils::sharedFileUtils()->getWritablePath();  
  12.     path += filename;  
  13.     if (CCFileUtils::sharedFileUtils()->isFileExist(CCFileUtils::sharedFileUtils()->fullPathForFilename(path.c_str())))  
  14.     {  
  15.         CCSprite* spr = CCSprite::create(path.c_str());  
  16.         node->addChild(spr);  
  17.         return;  
  18.     }  
  19.   
  20.     CCHttpRequest* request = new CCHttpRequest();  
  21.     this->node = node;  
  22.     this->filename = filename;  
  23.     if (this->node)  
  24.     {  
  25.         this->observerID = CCImageNotificationCenter::sharedImageNotificationCenter()->addObserver(filename,node,useMask);  
  26.     }  
  27.     request->setUrl(url);  
  28.     request->setRequestType(CCHttpRequest::kHttpGet);  
  29.     request->setResponseCallback(this, httpresponse_selector(CImageDownloader::HttpRequestComplete));  
  30.     CCImageNotificationCenter::sharedImageNotificationCenter()->m_ImageNotificationTarget = pTarget;  
  31.     CCImageNotificationCenter::sharedImageNotificationCenter()->m_pImageNotificationSelector = pSelector;  
  32.     request->setTag("GET IMAGE");  
  33.     CCHttpClient::getInstance()->send(request);  
  34.     request->release();  
  35. }  
  36.   
  37. void CImageDownloader::HttpRequestComplete(CCHttpClient *sender, CCHttpResponse *response)  
  38. {  
  39.     if (!response)  
  40.     {  
  41.         return;  
  42.     }  
  43.   
  44.     // You can get original request type from: response->request->reqType  
  45.     if (0 != strlen(response->getHttpRequest()->getTag()))  
  46.     {  
  47.         CCLog("%s completed", response->getHttpRequest()->getTag());  
  48.     }  
  49.   
  50.     int statusCode = response->getResponseCode();  
  51.     char statusString[64] = {};  
  52.     sprintf(statusString, "HTTP Status Code: %d, tag = %s", statusCode, response->getHttpRequest()->getTag());  
  53.     CCLog("response code: %d", statusCode);  
  54.   
  55.     if (!response->isSucceed())  
  56.     {  
  57.         CCLog("response failed");  
  58.         CCLog("error buffer: %s", response->getErrorBuffer());  
  59.         return;  
  60.     }  
  61.   
  62.     // dump data  
  63.     std::vector<char> *buffer = response->getResponseData();  
  64.     std::string path = CCFileUtils::sharedFileUtils()->getWritablePath();  
  65.     std::string bufffff(buffer->begin(),buffer->end());  
  66.   
  67.     //保存到本地文件  
  68.     path += this->filename;  
  69.     CCLOG("path: %s",path.c_str());  
  70.     FILE *fp = fopen(path.c_str(), "wb+");  
  71.     fwrite(bufffff.c_str(), 1,buffer->size(), fp);  
  72.     fclose(fp);  
  73.   
  74.     //传入node的下载请求会添加侦听,待下载完毕自动添加到node上  
  75.     if (this->node)  
  76.     {  
  77.         // node 是一个CCLayer ,用来显示动态加载的资源  
  78.         CCImageNotificationCenter::sharedImageNotificationCenter()->postNotification(this->observerID.getCString(), NULL);  
  79.     }  
  80. }  

  1. CImageNotificationCenter.h  
  2.   
  3. typedef void (CCObject::*SEL_ImageNotification)();  
  4. #define imagenotification_selector(_SELECTOR) (SEL_ImageNotification)(&_SELECTOR)  
  5.   
  6. //图片结构  
  7. class imgstruct : public CCObject  
  8. {  
  9. public:  
  10.     imgstruct(const char* iName, const char* idStr, CCNode* node, bool mask)  
  11.     {  
  12.         imageName = std::string(iName);  
  13.         observerId = std::string(idStr);  
  14.         this->node = node;  
  15.         useMask = mask;  
  16.     }  
  17.     ~imgstruct()  
  18.     {  
  19.     }  
  20.   
  21.     std::string imageName;  
  22.     std::string observerId;  
  23.     CCNode* node;  
  24.     //是否使用遮罩  
  25.     bool useMask;  
  26. };  
  27.   
  28. //图片监听,下载完成触发  
  29. class CCImageNotificationCenter : public CCNotificationCenter  
  30. {  
  31. public:  
  32.     static CCImageNotificationCenter* sharedImageNotificationCenter(void);  
  33.   
  34.     CCString addObserver(const char *imageName,CCNode* node,bool useMask);  
  35.     void imageLoaded();  
  36.     void removeObserver(const char *name);  
  37.   
  38.     void postNotification(const char *name, CCObject *object);  
  39.   
  40.     void imageLoaded(CCObject *obj);  
  41.   
  42.     static CCSprite* getSpriteFromWriteablePath(const char* name);  
  43.     //创建遮罩sprite  
  44.     static CCSprite* createMaskedSprite(CCSprite* src, const char* maskFile);  
  45. public:  
  46.     CCObject* m_ImageNotificationTarget;  
  47.     SEL_ImageNotification m_pImageNotificationSelector;  
  48. private:  
  49.     CCNotificationCenter        m_notificationCenter;  
  50.     int                         m_observerID;  
  51. };  

  1. CImageNotificationCenter.cpp  
  2.   
  3. CCImageNotificationCenter* CCImageNotificationCenter::sharedImageNotificationCenter( void )  
  4. {  
  5.     static CCImageNotificationCenter imageNotificationCenter;  
  6.     return &imageNotificationCenter;  
  7. }  
  8.   
  9. CCString CCImageNotificationCenter::addObserver(const char *imageName, CCNode* node, bool useMask)  
  10. {  
  11.     CCString* observerIDstr =  CCString::createWithFormat("%d",m_observerID);  
  12.   
  13.     m_notificationCenter.addObserver(this, callfuncO_selector(CCImageNotificationCenter::imageLoaded), observerIDstr->getCString(),   
  14.         new imgstruct(imageName, observerIDstr->getCString(), node, useMask));  
  15.   
  16.     m_observerID++;  
  17.     return observerIDstr->getCString();  
  18. }  
  19.   
  20. void CCImageNotificationCenter::removeObserver(const char *name)  
  21. {  
  22.     m_notificationCenter.removeObserver(this, name);  
  23. }  
  24.   
  25. void CCImageNotificationCenter::postNotification(const char *name, CCObject *object)  
  26. {  
  27.     m_notificationCenter.postNotification(name, object);  
  28. }  
  29.   
  30. void CCImageNotificationCenter::imageLoaded(CCObject *obj)  
  31. {  
  32.     imgstruct* img = (imgstruct*)obj;  
  33.     CCLOG("imageLoaded success,imageName:%s",img->imageName.c_str());  
  34.     CCSprite* sprite = CCImageNotificationCenter::getSpriteFromWriteablePath(img->imageName.c_str());  
  35.     CCLOG("got sprite 0x%X", sprite);  
  36.     if (img->useMask)  
  37.     {  
  38.         img->node->addChild(CCImageNotificationCenter::createMaskedSprite(sprite,"mask.png"));  
  39.     }  
  40.     else  
  41.     {  
  42.         float scale_ = (float) img->node->getContentSize().width  / (float)sprite->getContentSize().width;  
  43.         sprite->setAnchorPoint(ccp(0.5f,0.5f));  
  44.         //sprite->setScale(0.5f);  
  45.         img->node->addChild(sprite);  
  46.     }  
  47.     this->removeObserver(img->observerId.c_str());  
  48.     img->release();  
  49.   
  50.     (m_ImageNotificationTarget->*m_pImageNotificationSelector)();  
  51. }  
  52.   
  53.   
  54. CCSprite* CCImageNotificationCenter::getSpriteFromWriteablePath(const char* name)  
  55. {  
  56.     std::string path = CCFileUtils::sharedFileUtils()->getWritablePath();  
  57.     path += name;  
  58.     FILE* fp = fopen(path.c_str(),"rb");  
  59.     if (!fp)  
  60.     {  
  61.         return NULL;  
  62.     }  
  63.     fseek(fp,0,SEEK_END);  
  64.     int len = ftell(fp);  
  65.     fseek(fp,0,SEEK_SET);  
  66.     char* buf = (char*)malloc(len);  
  67.     fread(buf,len,1,fp);  
  68.     fclose(fp);  
  69.     CCImage* img = new CCImage;  
  70.     img->initWithImageData(buf,len);  
  71.     free(buf);  
  72.     cocos2d::CCTexture2D* texture = new cocos2d::CCTexture2D();  
  73.     bool isImg = texture->initWithImage(img);  
  74.     img->release();  
  75.     if (!isImg)  
  76.     {  
  77.         delete texture;  
  78.         return CCSprite::create("default.png");//加载资源并非图片时返回的默认图  
  79.     }  
  80.     CCSprite* sprite = CCSprite::createWithTexture(texture);  
  81.     texture->release();  
  82.     return sprite;  
  83. }  
  84.   
  85. CCSprite* CCImageNotificationCenter::createMaskedSprite( CCSprite* src, const char* maskFile )  
  86. {  
  87.     //创建遮罩 讲的还不错原理参考://http://blog.csdn.net/azymq/article/details/11110019  
  88.   
  89.     CCSprite * mask = CCSprite::create(maskFile);  
  90.   
  91.     assert(src);  
  92.     assert(mask);  
  93.   
  94.     CCSize srcContent = src->getContentSize();  
  95.     CCSize maskContent = mask->getContentSize();  
  96.   
  97.     CCRenderTexture * rt = CCRenderTexture::create(srcContent.width, srcContent.height, kTexture2DPixelFormat_RGBA8888);  
  98.   
  99.     float ratiow = srcContent.width / maskContent.width;  
  100.     float ratioh = srcContent.height / maskContent.height;  
  101.     mask->setScaleX(ratiow);  
  102.     mask->setScaleY(ratioh);  
  103.   
  104.     mask->setPosition(ccp(srcContent.width / 2, srcContent.height / 2));  
  105.     src->setPosition(ccp(srcContent.width / 2, srcContent.height / 2));  
  106.   
  107.     ccBlendFunc blendFunc2 = { GL_ONE, GL_ZERO };  
  108.     mask->setBlendFunc(blendFunc2);  
  109.     ccBlendFunc blendFunc3 = { GL_DST_ALPHA, GL_ZERO };  
  110.     src->setBlendFunc(blendFunc3);  
  111.   
  112.     rt->begin();  
  113.     mask->visit();  
  114.     src->visit();  
  115.     rt->end();  
  116.   
  117.     CCSprite * retval = CCSprite::createWithTexture(rt->getSprite()->getTexture());  
  118.     retval->setFlipY(true);  
  119.   
  120.     return retval;   
  121. }  

调用就比较简单了,直接

const char* url_item = "http://st1.tingall.com/UserData/HeadPics/465247/0.jpg36x36.jpg";
CImageDownloader* item = CImageDownloader::create();
item->SendHttpRequest(this, imagenotification_selector(CBagInterface::loadCompleteCallBack), url_item, rootNode, "item.jpg");


第二个参数是下载完成回调,方便做一些后续处理。。可以加载多张图片,并缓存到本地,代码已做判断本地是否已有该资源并作出相应的操作。。还有一些下载失败,文件验证这些没有加上


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值