cocos2dx拆分textpackture工具合成的plist大图集

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

这样就拆图成功了!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值