【Cocos2d-x】可以顯示線上圖片的CCSprite,cocos2d-xccsprite

來源:互聯網
上載者:User

【Cocos2d-x】可以顯示線上圖片的CCSprite,cocos2d-xccsprite


可以顯示線上圖片的CCSprite,使用HttpClient非同步請求圖片資料,當請求成功時,儲存圖片資料到本地,然後更新CCSprite的紋理,下載中時顯示預設圖片(可以設定預設圖片)。


OnlineImageSprite.h

#ifndef __ONLINEIMAGESPRITE_H__#define __ONLINEIMAGESPRITE_H__#include "cocos2d.h"USING_NS_CC;#include "cocos-ext.h"USING_NS_CC_EXT;// 可以顯示線上圖片的CCSpriteclass OnlineImageSprite:public CCSprite{public:/*建立一個顯示線上圖片的Sprite* defaultImagePath預設圖片路徑(當圖片載入中時顯示)* url圖片url*/static OnlineImageSprite* create(const char* defaultImagePath, const char* url);bool init(const char* defaultImagePath, const char* url);void onDownloadCompleted(CCHttpClient *sender, CCHttpResponse *response);protected:// 下載圖片void downloadImage(const char* url);// 擷取圖片路徑std::string getImagePath(const char* url);// 圖片是否存在bool isExist(const char* url);// 儲存圖片std::string saveImage(const std::string& data);private:const char* m_url;};#endif


OnlineImageSprite.cpp

#include "OnlineImageSprite.h"#include <string>using namespace std;   string&   replace_all(string&   str,const   string&   old_value,const   string&   new_value)   {   while(true)   {   string::size_type   pos(0);   if(   (pos=str.find(old_value))!=string::npos   )   str.replace(pos,old_value.length(),new_value);   else   break;   }   return   str;   }   string&   replace_all_distinct(string&   str,const   string&   old_value,const   string&   new_value)   {   for(string::size_type   pos(0);   pos!=string::npos;   pos+=new_value.length())   {   if(   (pos=str.find(old_value,pos))!=string::npos   )   str.replace(pos,old_value.length(),new_value);   else   break;   }   return   str;   }   OnlineImageSprite* OnlineImageSprite::create(const char* defaultImagePath, const char* url){OnlineImageSprite* pSprite = new OnlineImageSprite();if (pSprite && pSprite->init(defaultImagePath,url)){pSprite->autorelease();return pSprite;}CC_SAFE_DELETE(pSprite);return NULL;}bool OnlineImageSprite::init(const char* defaultImagePath, const char* url){m_url = url;CCTexture2D* pTexture = NULL;// 圖片是否存在,如果不存在使用預設紋理並下載圖片if (isExist(url)){const char* path = getImagePath(url).c_str();pTexture = CCTextureCache::sharedTextureCache()->addImage(path);}else{pTexture = CCTextureCache::sharedTextureCache()->addImage(defaultImagePath);// 下載圖片downloadImage(url);}// 初始化if (CCSprite::initWithTexture(pTexture)){return true;}return false;}//判斷圖片是否已經存在bool OnlineImageSprite::isExist(const char* url){std::string path = getImagePath(url);return CCFileUtils::sharedFileUtils()->isFileExist(path);}//擷取圖片全路徑std::string OnlineImageSprite::getImagePath(const char* url){std::string urlStr = url;replace_all(urlStr,"/","");replace_all(urlStr,"\\","");replace_all(urlStr,":","");replace_all(urlStr,".","");return CCFileUtils::sharedFileUtils()->getWritablePath().append("/").append(urlStr);}// 下載圖片void OnlineImageSprite::downloadImage(const char* url){// 發起http請求,下載圖片CCHttpRequest* request = new CCHttpRequest();request->setUrl(url);request->setRequestType(CCHttpRequest::kHttpGet);request->setResponseCallback(this, httpresponse_selector(OnlineImageSprite::onDownloadCompleted));CCHttpClient::getInstance()->send(request);request->release();}// 請求回調void OnlineImageSprite::onDownloadCompleted(CCHttpClient *sender, CCHttpResponse *response){if (!response){return;}// 返回碼int statusCode = response->getResponseCode();char statusString[64] = {};sprintf(statusString, "HTTP Status Code: %d", statusCode);CCLog("response code: %d", statusCode);// 請求失敗if (!response->isSucceed()) {CCLog("response failed");CCLog("error buffer: %s", response->getErrorBuffer());return;}// dump datastd::vector<char> *buffer = response->getResponseData();std::string data (buffer->begin(),buffer->end());std::string path =saveImage(data);//如果儲存圖片成功,更新紋理if (path != ""){CCTexture2D* pTexture = CCTextureCache::sharedTextureCache()->addImage(path.c_str());if (pTexture){setTexture(pTexture);}}}// 儲存圖片std::string OnlineImageSprite::saveImage(const std::string& data){std::string path = this->getImagePath(m_url);FILE* file = fopen(path.c_str(), "wb");if (file){// 1.buff// 2.每次寫的位元組數// 3.寫多少次結束// 4.檔案控制代碼fwrite(data.c_str(), 1,data.length(), file);fclose(file);return path;}return "";}

使用樣本:
//建立OnlineImageSpirte,參數:1.預設圖片路徑 2.線上圖片的urlCCSprite* pSprite = OnlineImageSprite::create("HelloWorld.png","http://cc.cocimg.com/cocos2dx/image/logo.png");//設定位置pSprite->setPosition(ccp(visibleSize.width/2 + origin.x, visibleSize.height/2 + origin.y));//添加到Layerthis->addChild(pSprite, 0);

項目地址:https://coding.net/u/linchaolong/p/OnlineImageSprite/git


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.