Overview of new gui¶

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.

NameDescriptionNameDescription
WidgetBase class of all the GUI elementsLoadingBarLoading prograss bar
LayoutIt's a container to manage various widgetsScrollViewScrolling view
Scale9Spritea sprite which enable slice 9ListViewAlso know as TableView
Buttona clickable button with slice 9 enabledSliderSlider bar
CheckBoxCheck boxTextFieldA control to allow you input some texts
ImageViewa control to display an imageTextBMFonta BMFont labels
TextCharacter labelPageViewPage view
HelperHelp 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++:


 
 
1
2
3
4
5
6
7
8
9
10
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


 
 
1
2
3
4
5
6
7
    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 MethodsDescription
setString(const std::string& text)Setting of display text label
getString()Get displayed text
getLength()Get the length of string(Chinese character is more than English's, in iOS is 3)
setFontName(const std::string& name)Set font
setFontSize(int size)Set the size of font
setScale(float fScale)Set the scale factor
setAnchorPoint(const cocos2d::Point &pt)Set the position of the anchor
setTouchEnabled(bool enable)Enable the touch
setTouchScaleChangeEnabled(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 adding addTouchEventListener.

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++:


 
 
1
2
3
4
5
6
7
    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:


 
 
1
2
3
4
5
6
     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 of touchEvent 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++


 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
    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


 
 
1
2
3
4
5
6
7
8
9
10
11
 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 methodsDescription
setTouchEnabled(bool enable)Enable touch, default is disabled
loadTextures(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 position
addTouchEventListener(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 enable setTouchEnabled, 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**


 
 
1
2
3
4
   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 methodsDescription
loadTexture(const char* fileName,TextureResType texType =TextureResType::LOCAL);The method of image display widget loading image resource
setTextureRect(const Rect& rect)Set image's rectangle area
setScale9Enabled(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++


 
 
1
2
3
4
5
6
    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


 
 
1
2
3
4
   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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值