分享一段利用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文件夹,里面就是拆分出来的图片
这样就拆图成功了!!!