在cocos2dx中解析plist文件

先保存,备用

plist文件实际上就是xml文件,默认情况下,我用TexturePacker生成的纹理中会对应一个plist文件,通过plist文件的信息,可以知道纹理中各个小图片的位置和大小。我生成的plist文件如下图:

cocos2dx对解析这类的文件提供了不错的支持:

/**************************

*PlistUtil.h

****************************/

#ifndef __PlistUtil_H__

#define __PlistUtil_H__


#include "cocos2d.h"


USING_NS_CC;


class PlistUtil:public CCObject

{

public:

/* 获取工具对象,单例方式 */

static PlistUtil* sharedPlistUtil();


/* 初始化 */

bool init();


/* 加载配置文件,在读取一个新配置文件之前要调一次 */

void loadFile(const char* sPath);


/* 释放配置文件,配置文件用完后应该马上调用它释放资源 */

void releaseFile(const char* sPath);


/* 根据图片名称从纹理图中获取图片的位置和大小,便于精灵批量绘制*/

CCRect getResourceRect(const char* resourceName,const char* filePath);


private:

/* 单例对象*/

static  PlistUtil* mPlistUtil;


/* 

        存放mFileDictt-filePath的字典。

        这样写比较好记忆:CCDictionary<CCArray<CCArray>, const char*>

    */

CCDictionary* mFileDict;

};


#endif


/******************************

*PlistUtil.cpp

******************************/

#include "PlistUtil.h"


PlistUtil* PlistUtil::mPlistUtil = NULL;


PlistUtil* PlistUtil::sharedPlistUtil(){

if(mPlistUtil == NULL) {

mPlistUtil = new PlistUtil();

if(mPlistUtil && mPlistUtil->init()) {

mPlistUtil->autorelease();

}

else {

CC_SAFE_DELETE(mPlistUtil);

mPlistUtil = NULL;

}

}


return mPlistUtil;

}


bool PlistUtil::init(){


/* 初始化成员变量 */

mFileDict = CCDictionary::create();

mFileDict->retain();


return true;

}


void PlistUtil::loadFile(const char* sPath)

{

CCDictionary* plistDic = CCDictionary::createWithContentsOfFile(sPath);

if(NULL!=plistDic)

{

CCDictionary* frames=dynamic_cast<CCDictionary*>(plistDic->objectForKey("frames"));

if(NULL!=frames)

{

mFileDict->setObject(frames,sPath);

}

}

}


void PlistUtil::releaseFile( const char* sPath )

{

mFileDict->removeObjectForKey(sPath);

}


CCRect PlistUtil::getResourceRect(const char* resourceName,const char* filePath)

{

CCDictionary* frames=(CCDictionary*)mFileDict->objectForKey(filePath);

if(NULL!=frames)

{

CCDictionary* tmpDict=dynamic_cast<CCDictionary*>(frames->objectForKey(resourceName));

if(NULL!=tmpDict)

{

return CCRectFromString(

dynamic_cast<CCString*>(tmpDict->objectForKey("frame"))->getCString());

}

}

return CCRectMake(0,0,0,0);

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值