分享一段利用cocos2dx中RenderTexture截圖功能來拆分plist大圖集的源代碼。
函數聲明:
//解析plist大圖集,imgPath:png大圖。plistPath:plist文件
void DecodePlist(const std::string &imgPath, const std::string &plistPath);
函數實現:
#include <direct.h>
using namespace std;
void HelloWorld::DecodePlist(const std::string &imgPath, const std::string &plistPath)
{
//將大圖添加到幀緩存池中
SpriteFrameCache::getInstance()->addSpriteFramesWithFile(plistPath, imgPath);
//創建一個和plist文件同名的目錄,用來存放拆分出來的小圖片
string dirName = plistPath;
size_t pos = plistPath.find_last_of("/");
if (pos != string::npos)dirName = plistPath.substr(plistPath.find_last_of("/") + 1);
pos = dirName.find(".plist");
if (pos != string::npos)
{
dirName = dirName.substr(0, dirName.find(".plist"));
string dirPath = FileUtils::getInstance()->getWritablePath() + dirName;
//在可寫路徑下創建目錄(和plist同名)
int ret = mkdir(dirPath.c_str()); // 返回 0 表示創建成功,-1 表示失敗
if (ret ==0)CCLOG("create dir succeed");
else CCLOG("create dir failed");
}
else{
CCLOG("plist file error");
return;
}
//讀取plist文件數據
ValueMap plistDic = FileUtils::getInstance()->getValueMapFromFile(plistPath);
if (plistDic.find("frames") != plistDic.end())
{
ValueMap framesDic = plistDic["frames"].asValueMap();
for (auto it = framesDic.begin(); it != framesDic.end(); it++)
{
//當前圖片的名字
string imgName = it->first;
//將要保存的文件路徑
string savePath = dirName + "/" + imgName;
if (savePath.find(".png") == string::npos) savePath += ".png";
//創建精靈
auto sp = Sprite::createWithSpriteFrameName(imgName);
if (sp != nullptr)
{
Size imgSize = sp->getContentSize();
RenderTexture *pRenderTexture = RenderTexture::create(imgSize.width, imgSize.height);
pRenderTexture->begin();
//因爲pRenderTexture錨點默認是左下角,所以把精靈的錨點也設置成左下角,這樣纔不會錯位
sp->setAnchorPoint(Vec2(0, 0));
sp->visit();
pRenderTexture->end();
pRenderTexture->saveToFile(savePath, Image::Format::PNG);
CCLOG("save img %s", savePath.c_str());
}
}
}
}
調用方式:
//解析Resources目錄下面的UI.plist和UI.png大圖集
DecodePlist("UI.png", "UI.plist");
這個UI.png和UI.plist文件是我放在Resources目錄下面的測試文件。
程序運行之後,在工程的Debug目錄下就會創建一個UI文件夾,裏面就是拆分出來的圖片
這樣就拆圖成功了!!!