首先在头文件中加上以下代码
#include "cocos2d.h"
#include "cocos-ext.h"
USING_NS_CC;
USING_NS_CC_EXT;
using namespace ui;
以上代码在2.2.3中已经帮大家包含了.不用额外的去进行项目设置,以下
class HelloWorld : public cocos2d::CCLayer
{
public:
HelloWorld();
~HelloWorld() {;}
// Here's a difference. Method 'init' in cocos2d-x returns bool, instead of returning 'id' in cocos2d-iphone
virtual bool init();
// there's no 'id' in cpp, so we recommend returning the class instance pointer
static cocos2d::CCScene* scene();
// a selector callback
void menuCloseCallback(CCObject* pSender);
// implement the "static node()" method manually
CREATE_FUNC(HelloWorld);
TouchGroup* _touchGroup;
Layout* _layout;
void menuCallback(CCObject* pSender, TouchEventType type);
};
以下是CPP文件的绑定
bool HelloWorld::init()
{
//
// 1. super init first
if ( !CCLayer::init() )
{
return false;
}
per = 0;
CCSize visibleSize = CCDirector::sharedDirector()->getVisibleSize();
CCPoint origin = CCDirector::sharedDirector()->getVisibleOrigin();
/
// 2. add a menu item with "X" image, which is clicked to quit the program
// you may modify it.
// add a "close" icon to exit the progress. it's an autorelease object
CCMenuItemImage *pCloseItem = CCMenuItemImage::create(
"CloseNormal.png",
"CloseSelected.png",
this,
menu_selector(HelloWorld::menuCloseCallback));
pCloseItem->setPosition(ccp(origin.x + visibleSize.width - pCloseItem->getContentSize().width/2 ,
origin.y + pCloseItem->getContentSize().height/2));
// create menu, it's an autorelease object
CCMenu* pMenu = CCMenu::create(pCloseItem, NULL);
pMenu->setPosition(CCPointZero);
this->addChild(pMenu, 1);
// /
// // 3. add your codes below...
//
_touchGroup = TouchGroup::create();
addChild(_touchGroup);
/加载cocostudio的布局文件///
_layout = static_cast<Layout*>(GUIReader::shareReader()->widgetFromJsonFile("test.json"));
_touchGroup->addWidget(_layout);
CCSize screenSize = CCDirector::sharedDirector()->getWinSize();
CCSize rootSize = _layout->getSize();
_touchGroup->setPosition(CCPoint((screenSize.width - rootSize.width) / 2,
(screenSize.height - rootSize.height) / 2));
Layout* root = static_cast<Layout*>(_touchGroup->getWidgetByName("Panel_2383"));
return true;
}
只要这么2行代码,就可以把之前在cocostudio里面的布局文件加载进来,是不是很方便呢?不管多么复杂的文件,都只要这两行就可以全部加载进来(静态布局),如果有按钮,scrollview,checkbox等,还需要进行回调函数的绑定!总之cocostudio的出现大大降低了界面上对齐排版的工作量.
当然了,这个.json文件需要从cocostudio里面进行导出,也是非常方便的.