Overview of new gui¶

来源:互联网 发布:深圳众诚网络 编辑:程序博客网 时间:2024/05/24 06:34

Overview of new gui

Introduction

It was difficult to design complex UI before GUI system was introduced. Even if you can design specific UI for specific kind of game, such as MMORPG, still you can't reach your expectation because of abundant of UI. We can design a GUI system ourselves, but it's a huge program to pursue. Now Cocos2d-x has its own solution-GUI system. Let's get started.

GUI Widgets

Let's take a glance of these widgets in following list. Details about these widgets will be shown later.

NameDescriptionNameDescriptionWidgetBase class of all the GUI elementsLoadingBarLoading prograss barLayoutIt's a container to manage various widgetsScrollViewScrolling viewScale9Spritea sprite which enable slice 9ListViewAlso know as TableViewButtona clickable button with slice 9 enabledSliderSlider barCheckBoxCheck boxTextFieldA control to allow you input some textsImageViewa control to display an imageTextBMFonta BMFont labelsTextCharacter labelPageViewPage viewHelperHelp classTextAtlasan atlas label

Usage of General Widgets

Let's get started with Hello Cocos

Every element in GUI system is a Widget element and a Widget is inherited from cocos2d::Ref class. Now Widget element are inherited from cocos2d::Node class, so all the Node descendants could be added into the Widget tree.

In C++:

12345678910
auto size = Director::getInstance()->getWinSize();auto label = Text::create();label->setText("Hello Cocos!");label->setFontName("Marker Felt");label->setFontSize(30);label->setColor(Color3B(159, 168, 176));label->setPosition(Point(size.width / 2, size.height / 2));addChild(label);

In Lua

1234567
    self._displayValueLabel = ccui.Text:create()    self._displayValueLabel:setString("No Event")    self._displayValueLabel:setFontName(font_UIButtonTest)    self._displayValueLabel:setFontSize(32)    self._displayValueLabel:setAnchorPoint(cc.p(0.5, -1))    self._displayValueLabel:setPosition(cc.p(widgetSize.width / 2.0, widgetSize.height / 2.0))    self._uiLayer:addChild(self._displayValueLabel)

hello_cocos

In addtion, Text class has other properties:

General properties and MethodsDescriptionsetString(const std::string& text)Setting of display text labelgetString()Get displayed textgetLength()Get the length of string(Chinese character is more than English's, in iOS is 3)setFontName(const std::string& name)Set fontsetFontSize(int size)Set the size of fontsetScale(float fScale)Set the scale factorsetAnchorPoint(const cocos2d::Point &pt)Set the position of the anchorsetTouchEnabled(bool enable)Enable the touchsetTouchScaleChangeEnabled(bool enable)Enable zoom when touch(enable touch is required)

Text usually used for display static text, but you can also get the same function by addingaddTouchEventListener.

Usage of Button

The code below shown a Text and then we'll add a Button. When touch the Button the content of the Text will be changed:

In C++:

1234567
    auto uButton = Button::create();    uButton->setTouchEnabled(true);    uButton->loadTextures("cocosgui/animationbuttonnormal.png", "cocosgui/animationbuttonpressed.png", "");    uButton->setPosition(Point(size.width / 2, size.height / 2) + Point(0, -50));    uButton->addTouchEventListener(this, toucheventselector(HelloWorld::touchEvent));    uLayer->addWidget(uButton);

In Lua:

123456
     local button = ccui.Button:create()    button:setTouchEnabled(true)    button:loadTextures("cocosui/animationbuttonnormal.png", "cocosui/animationbuttonpressed.png", "")    button:setPosition(cc.p(widgetSize.width / 2.0, widgetSize.height / 2.0))            button:addTouchEventListener(touchEvent)    self._uiLayer:addChild(button)

We used addTouchEventListener to add touch event callback function. The implementation oftouchEvent in the following code will show you how it listens the every status of the button(such as click, move, end touch and cancel touch):

Note: _lbl is a private variable and the reference of the Text.

In C++

12345678910111213141516171819202122
    void HelloWorld::touchEvent(Ref *pSender, TouchEventType type)    {        switch (type)        {            case ui::Widget::TouchEventType::BEGAN:                _lbl->setText("UIButton Click.");                break;            case ui::Widget::TouchEventType::MOVED:                // TODO                break;            case ui::Widget::TouchEventType::ENDED:                // TODO                break;            case ui::Widget::TouchEventType::CANCELED:                // TODO                break;            default:                // TODO                break;        }    }

In Lua

1234567891011
 local function touchEvent(sender,eventType)        if eventType == ccui.TouchEventType.began then            self._displayValueLabel:setString("Touch Down")        elseif eventType == ccui.TouchEventType.moved then            self._displayValueLabel:setString("Touch Move")        elseif eventType == ccui.TouchEventType.ended then            self._displayValueLabel:setString("Touch Up")        elseif eventType == ccui.TouchEventType.canceled then            self._displayValueLabel:setString("Touch Cancelled")        end    end   

uibutton

General properties and methodsDescriptionsetTouchEnabled(bool enable)Enable touch, default is disabledloadTextures(const char* normal,const char* selected,const char* disabled,TextureResType texType = TextureResType::LOCAL);Loading button image resource, such as normal status, pressed status and disabled status.setPosition(const Point &pos)Set widget's positionaddTouchEventListener(Object *target, SEL_TouchEvent selector)Set button's callback function

Note: Some widgets can not enable touch, such as Text and ImageView, however, Button and ScrollView must enablesetTouchEnabled, and this function is inherited from Widget.

General properties and Usages of ImageView

To enrich the UI we added a image display widget-ImageView, as following code:

In C++:

    ImageView *imageView = ImageView::create();    imageView->loadTexture("cocosgui/ccicon.png");    imageView->setPosition(Point(size.width / 2, size.height / 2) + Point(0, 50));    this->addWidget(imageView);

** In Lua**

1234
   local imageView = ccui.ImageView:create()    imageView:loadTexture("cocosui/ccicon.png")    imageView:setPosition(cc.p(widgetSize.width / 2.0, widgetSize.height / 2.0 + imageView:getContentSize().height / 4.0))    self._uiLayer:addChild(imageView)

uiimageview

General properties and methodsDescriptionloadTexture(const char* fileName,TextureResType texType =TextureResType::LOCAL);The method of image display widget loading image resourcesetTextureRect(const Rect& rect)Set image's rectangle areasetScale9Enabled(bool able)Enable Scale9 image

Import resource from CocoStudio

We've got the basic steps to use widgets by the contents we've mentioned above. First we should create some UI widgets, then adding them into a layer or scene. In the meantime, set some general properties such as click when you need interaction actions. If the widgets are not too much we can easily manage it, however, when the UI widgets are too much to control it maybe a trouble. So we introduce a new way to load UI resource by CocoStudio.

What are the advantages of using CocoStudio? CocoStudio UI editor allows you preview the result you just designed by every widgets in the editor. It saves you much time to code for the widgets properties because you can set them in the editor. For example, you can set ImageView display image, set Text display text, set button image for Button and enable touch. It's efficient to use CocoStudio and GUI lib together.

Load GUI Resource

Now we use the method provided by cocostudio::GUIReader loading UI widgets from json file:

In C++

123456
    Layout* m_pLayout = dynamic_cast<UILayout*>(cocostudio::GUIReader::shareReader()->widgetFromJsonFile("cocosgui/UITest/UITest.json"));    this->addChild(m_pLayout);    Text* m_pSceneTitle = dynamic_cast<Text*>(m_pLayout->getWidgetByName("UItest"));

In Lua

1234
   self._layout = ccs.GUIReader:getInstance():widgetFromJsonFile("cocosui/UIEditorTest/UIButton_Editor/UIButton_Editor_1.json")    self._uiLayer:addChild(self._layout)    local sceneTitle = self._layout:getChildByName("UItest")   

Note: The UITest.json file here is generated by CocoStudio UI editor, usually we don't change the content to change every property. You can find more details about how to use CocoStudio from CocoStudio document.

UITest.json file contains all the defines of UI, layout of UI and every setting of properties. When GUIReader loaded resource, corresponding widgets can be created and fill their properties. By using CocoStudio UI editor saves a lot of coding work.

UI Resource Using Procedure

As discussed, the first resource you got from UI resource is a Layout resource, and it's the Panel widget in CocoStudio. It always be the root widget of UI widget for layout work. We can add Button, Text, CheckBox, ImageView and Scrollview, etc to Panel. Also, it's possible to add a Panel as sub-area to a Panel. This json file is a dictionary data structure, which "key" stores the property name and "value" stores the value. There is no concern about the implementation of the GUIReader.

When Layout added to a layout, we can use layout->getWidgetByName("UItest") to get a exists widget in UI resource from Layout.Note: The getWidgetByName() method here belongs to Layout. Remember Layout is just one kind of widget.

0 0
原创粉丝点击