【cocos2d-x】cocos2dx之儲存,cocos2d-xcocos2dx
遊戲過程中,偶爾需要和儲存圖片,但是cocos2d-x本身對這方面的支援比較少,所以只能用比較特殊的方法來儲存~
RenderTexture
RenderTexture是一個通用渲染對象,可以通過構建一個RenderTexture對象,進而把要渲染的東西填充進去,在渲染開始前調用call函數,調用cocos的情境的visit函數對其進行渲染,渲染結束後調用end函數。RenderTexture繼承於Node,所以可以簡單地把渲染紋理添加到你的情境中,就像處理其它cocos中的節點一樣,當然它還提供了儲存功能,可以把渲染紋理儲存為PNG或JPG格式。
(引用自http://blog.csdn.net/jackystudio/article/details/15498083)
比如
Sprite *sprite = Sprite::create("HelloWorld.png");sprite -> setAnchorPoint(Point(0, 0));RenderTexture *renderTexture = RenderTexture::create(480, 320, Texture2D::PixelFormat::RGBA8888);renderTexture -> begin();sprite -> visit();renderTexture -> end();renderTexture -> saveToFile(StringUtils::format("demo.png"), Image::Format::PNG);
上面的代碼就吧HelloWorld.png 儲存成demo.png,儲存在哪裡呢? 可以通過getWritablePath()得到
log("%s", FileUtils::getInstance() -> getWritablePath().c_str());
如果你需要截取整個螢幕的話,那就把上面的sprite換成Director::getInstance() -> getRunningScene(),當然在3.x裡還有更簡便的方法
utils::captureScreen(CC_CALLBACK_2(HelloWorld::capture, this), "screenshot.png");//capturevoid HelloWorld::capture(bool succeed, const std::string& outputFile){ if (succeed) { log("%s", outputFile); }}
只需要一條語句加一個回呼函數就可以搞定~
最後貼一個用RenderTexture把動畫大圖中的小圖取出來存放的Demo,效果:
截取前:
截取後:(圖片取自PlantNanny)
圖片和代碼下載
歡迎訪問我的個人部落格:helkyle.tk