UI Elements
This page will cover the UI elements provided as an extension to Cocos.
UI elements allow complex menus and other game interfaces to be created. UI is an extension to Cocos and therefore needs to be added so your project can make use of it. The code is already there but it just needs to be included so it can be used.
UI elements like most things in Cocos are nodes hence all the functions for nodes can be used on them.
Setting Up A Cocos2d-JS Project For UI Elements
Open the project.json file which is located at the root of your project. Modify the following line:
"modules" :["cocos2d"],
so it includes the extensions module:
"modules" :["cocos2d", "extensions"],
Example project.json:
{
"project_type": "javascript",
"debugMode" : 1,
"showFPS" : true,
"frameRate" : 60,
"id" : "gameCanvas",
"renderMode" : 0,
"engineDir":"frameworks/cocos2d-html5",
"modules" : ["cocos2d"],
"jsList" : [
"src/resource.js",
"src/app.js"
]
}
{
"project_type": "javascript",
"debugMode" : 1,
"showFPS" : true,
"frameRate" : 60,
"id" : "gameCanvas",
"renderMode" : 0,
"engineDir":"frameworks/cocos2d-html5",
"modules" : ["cocos2d", "extensions"],
"jsList" : [
"src/resource.js",
"src/app.js"
]
}
Setting Up A Cocos2d-x C++ Project For UI Elements
In any .h or .cpp file you would like to use UI elements inside add the following code to the top of the page:
#include "extensions/cocos-ext.h"
#include "ui/CocosGUI.h"
USING_NS_CC_EXT;
using namespace ui; // if this line isn't included then each UI object will need to be created using ui::
The following will work for iOS but for Android a bit of extra code is required. Open the Android.mk file located in at ProjectRoot/proj.android/jni/. Add the following code to the file:
// this should be added below the other LOCAL_WHOLE_STATIC_LIBRARIES inside the file
LOCAL_WHOLE_STATIC_LIBRARIES += cocos_extension_static
LOCAL_WHOLE_STATIC_LIBRARIES += cocos_ui_static
// this should be added below the other module imports inside the file
$(call import-module,extensions)
$(call import-module,ui)
Note: *The above lines maybe already exist inside the Android.mk file. If there is a # at the start of the line then it is commented out. To uncomment it just simply remove the #*
Example Android.mk:
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
$(call import-add-path,$(LOCAL_PATH)/../../cocos2d)
$(call import-add-path,$(LOCAL_PATH)/../../cocos2d/external)
$(call import-add-path,$(LOCAL_PATH)/../../cocos2d/cocos)
LOCAL_MODULE := cocos2dcpp_shared
LOCAL_MODULE_FILENAME := libcocos2dcpp
LOCAL_SRC_FILES := hellocpp/main.cpp \
../../Classes/AppDelegate.cpp \
../../Classes/HelloWorldScene.cpp
LOCAL_C_INCLUDES := $(LOCAL_PATH)/../../Classes
LOCAL_WHOLE_STATIC_LIBRARIES := cocos2dx_static
LOCAL_WHOLE_STATIC_LIBRARIES += cocosdenshion_static
# LOCAL_WHOLE_STATIC_LIBRARIES += box2d_static
# LOCAL_WHOLE_STATIC_LIBRARIES += cocosbuilder_static
# LOCAL_WHOLE_STATIC_LIBRARIES += spine_static
# LOCAL_WHOLE_STATIC_LIBRARIES += cocostudio_static
# LOCAL_WHOLE_STATIC_LIBRARIES += cocos_network_static
# LOCAL_WHOLE_STATIC_LIBRARIES += cocos_extension_static
include $(BUILD_SHARED_LIBRARY)
$(call import-module,.)
$(call import-module,audio/android)
# $(call import-module,Box2D)
# $(call import-module,editor-support/cocosbuilder)
# $(call import-module,editor-support/spine)
# $(call import-module,editor-support/cocostudio)
# $(call import-module,network)
# $(call import-module,extensions)
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
$(call import-add-path,$(LOCAL_PATH)/../../cocos2d)
$(call import-add-path,$(LOCAL_PATH)/../../cocos2d/external)
$(call import-add-path,$(LOCAL_PATH)/../../cocos2d/cocos)
LOCAL_MODULE := cocos2dcpp_shared
LOCAL_MODULE_FILENAME := libcocos2dcpp
LOCAL_SRC_FILES := hellocpp/main.cpp \
../../Classes/AppDelegate.cpp \
../../Classes/HelloWorldScene.cpp
LOCAL_C_INCLUDES := $(LOCAL_PATH)/../../Classes
LOCAL_WHOLE_STATIC_LIBRARIES := cocos2dx_static
LOCAL_WHOLE_STATIC_LIBRARIES += cocosdenshion_static
# LOCAL_WHOLE_STATIC_LIBRARIES += box2d_static
# LOCAL_WHOLE_STATIC_LIBRARIES += cocosbuilder_static
# LOCAL_WHOLE_STATIC_LIBRARIES += spine_static
# LOCAL_WHOLE_STATIC_LIBRARIES += cocostudio_static
# LOCAL_WHOLE_STATIC_LIBRARIES += cocos_network_static
LOCAL_WHOLE_STATIC_LIBRARIES += cocos_extension_static
LOCAL_WHOLE_STATIC_LIBRARIES += cocos_ui_static
include $(BUILD_SHARED_LIBRARY)
$(call import-module,.)
$(call import-module,audio/android)
# $(call import-module,Box2D)
# $(call import-module,editor-support/cocosbuilder)
# $(call import-module,editor-support/spine)
# $(call import-module,editor-support/cocostudio)
# $(call import-module,network)
$(call import-module,extensions)
$(call import-module,ui)
UIButton - a clickable button
Button *button = Button::create( "Normal image filepath", "Selected image filepath" );
var button = new ccui.Button();
button.loadTextures( "Normal image filepath", "Selected image filepath" );
To detect when the user interacts with the button a touch event listener needs to be attached to it.
void touchEvent( Ref *sender, Widget::TouchEventType type );
// this is used to assign the touch event listener (usually is coded when the button is constructed)
button->addTouchEventListener( CC_CALLBACK_2( ClassName::touchEvent, this ) );
// this is called when the user interacts with the button
void ClassName::touchEvent( Ref *sender, Widget::TouchEventType type )
{
switch (type)
{
case Widget::TouchEventType::BEGAN:
// code to handle when the button is first clicked
break;
case Widget::TouchEventType::MOVED:
// code to handle when the user is moving their finger/cursor whilst clicking the button
break;
case Widget::TouchEventType::ENDED:
// code to handle when the button click has ended (e.g. finger is lifted off the screen)
break;
case Widget::TouchEventType::CANCELED:
// code to handle when the button click has been cancelled, this is usually handled the same way as ENDED in most applications (e.g. another application takes control of the device)
break;
default:
break;
}
}
// this is used to assign the touch event listener (usually is coded when the button is constructed)
button.addTouchEventListener( this.touchEvent, this );
// this is called when the user interacts with the button
touchEvent: function(sender, type)
{
switch (type)
{
case ccui.Widget.TOUCH_BEGAN:
// code to handle when the button is first clicked
break;
case ccui.Widget.TOUCH_MOVED:
// code to handle when the user is moving their finger/cursor whilst clicking the button
break;
case ccui.Widget.TOUCH_ENDED:
// code to handle when the button click has ended (e.g. finger is lifted off the screen)
break;
case ccui.Widget.TOUCH_CANCELLED:
// code to handle when the button click has been cancelled, this is usually handled the same way as ENDED in most applications (e.g. another application takes control of the device)
break;
}
}
UICheckBox - a checkbox for binary selection
CheckBox *checkBox = CheckBox::create( "Checkbox normal image file path",
"Checkbox normal pressed image filepath",
"Checkbox active image filepath",
"Checkbox normal disabled image filepath",
"Checkbox active disabled image filepath" );
var checkBox = new ccui.CheckBox( );
checkBox.loadTextures( "Checkbox normal image file path",
"Checkbox normal pressed image filepath",
"Checkbox active image filepath",
"Checkbox normal disabled image filepath",
"Checkbox active disabled image filepath" );
To detect when the user interacts with the checkbox a touch event listener needs to be attached to it.
void selectedEvent( Ref *sender, CheckBox::EventType type );
// this is used to assign the touch event listener (usually is coded when the checkbox is constructed)
checkBox->addEventListener( CC_CALLBACK_2( ClassName::selectedEvent, this ) );
// this is called when the user interacts with the checkbox
void ClassName::selectedEvent(Ref *sender, CheckBox::EventType type )
{
switch (type)
{
case CheckBox::EventType::SELECTED:
// code for when the checkbox has been clicked and is now selected (binary 1)
break;
case CheckBox::EventType::UNSELECTED:
// code for when the checkbox has been clicked and is now not selected (binary 0)
break;
default:
break;
}
}
// this is used to assign the touch event listener (usually is coded when the checkbox is constructed)
checkBox.addEventListener( this.selectedStateEvent, this );
// this is called when the user interacts with the checkbox
selectedStateEvent: function ( sender, type )
{
switch ( type )
{
case ccui.CheckBox.EVENT_SELECTED:
// code for when the checkbox has been clicked and is now selected (binary 1)
break;
case ccui.CheckBox.EVENT_UNSELECTED:
// code for when the checkbox has been clicked and is now not selected (binary 0)
break;
default:
break;
}
}
UIEditBox - an input field
ui::EditBox *editName = ui::EditBox::create( Size( 900, 60 ), ui::Scale9Sprite::create( "Background image file path" ) );
editName->setPosition( Vec2( origin.x + visibleSize.width / 2, origin.y + visibleSize.height * 3 / 4 ) );
editName->setFontName( "Font location" );
editName->setFontSize( 25 );
editName->setFontColor( Color3B::RED );
editName->setPlaceHolder( "Name:" );
editName->setPlaceholderFontColor( Color3B::WHITE );
editName->setMaxLength( 8 );
editName->setReturnType( ui::EditBox::KeyboardReturnType::DONE );
editName->setDelegate( this );
this->addChild( editName );
To detect when the user interacts with the EditBox your class will need to inherit from EditBoxDelegate.
class ClassName : public cocos2d::Layer
// becomes
class ClassName : public cocos2d::Layer, public cocos2d::ui::EditBoxDelegate
virtual void editBoxEditingDidBegin( cocos2d::ui::EditBox *editBox );
virtual void editBoxEditingDidEnd( cocos2d::ui::EditBox *editBox );
virtual void editBoxTextChanged( cocos2d::ui::EditBox *editBox, const std::string &text );
virtual void editBoxReturn( cocos2d::ui::EditBox *editBox );
void ClassName::editBoxEditingDidBegin( cocos2d::ui::EditBox *editBox )
{
log( "Did Begin" );
}
void ClassName::editBoxEditingDidEnd( cocos2d::ui::EditBox *editBox )
{
log( "Did End");
}
void ClassName::editBoxTextChanged( cocos2d::ui::EditBox *editBox, const std::string &text )
{
log( "Text Changed, text: %s", text.c_str( ) );
}
void ClassName::editBoxReturn( ui::EditBox *editBox )
{
log( "Returned" );
}
UIImageView - simply displays an arbitrary image
ImageView *imageView = ImageView::create( "Image filepath" );
var imageView = new ccui.ImageView( );
imageView.loadTexture( "Image filepath" );
UILayout - allows you to group nodes together
Layout *layout = Layout::create( );
// Layout::Type::VERTICAL, Layout::Type::HORIZONTAL, Layout::Type::ABSOLUTE or Layout::Type::RELATIVE
layout->setLayoutType( Layout::Type::VERTICAL );
// Widget::SizeType::ABSOLUTE or Widget::SizeType::PERCENT
layout->setSizeType( Widget::SizeType::ABSOLUTE );
layout->setSizePercent( Vec2( 0.5, 0.5 ) );
// Widget::PositionType::ABSOLUTE or Widget::PositionType::PERCENT
layout->setPositionType( Widget::PositionType::ABSOLUTE );
layout->setPositionPercent( Vec2( 0.25, 0.25 ) );
// Layout::BackGroundColorType::GRADIENT, Layout::BackGroundColorType::NONE or Layout::BackGroundColorType::SOLID
layout->setBackGroundColorType( Layout::BackGroundColorType::GRADIENT );
layout->setBackGroundColor( Color3B::GRAY );
// add node to layout
layout->addChild( nodeToAdd );
var layout = new ccui.Layout();
// LINEAR_HORIZONTAL or LINEAR_VERTICAL
layout.setLayoutType( ccui.Layout.LINEAR_HORIZONTAL );
// ccui.Widget.SIZE_PERCENT or ccui.Widget.SIZE_ABSOLUTE
layout.sizeType = ccui.Widget.SIZE_PERCENT;
layout.setSizePercent( cc.p( 0.5, 0.5 ) );
// ccui.Widget.POSITION_PERCENT or ccui.Widget.POSITION_ABSOLUTE
layout.setPositionType( ccui.Widget.POSITION_PERCENT );
layout.setPositionPercent( cc.p( 0.25, 0.25 ) );
// ccui.Layout.BG_COLOR_GRADIENT, ccui.Layout.BG_COLOR_NONE or ccui.Layout.BG_COLOR_SOLID
layout.setBackGroundColorType( ccui.Layout.BG_COLOR_SOLID );
layout.setBackGroundColor( cc.color.GRAY );
// add node to layout
layout.addChild( nodeToAdd );
UIListView - a view allowing you to contain other UI elements which the user can scroll through
ListView *listView = ListView::create( );
// scroll direction (ui::ScrollView::Direction::VERTICAL or ui::ScrollView::Direction::HORIZONTAL)
listView->setDirection( ui::ScrollView::Direction::VERTICAL );
listView->setClippingEnabled( false );
listView->setPosition( Vec2( visibleSize.width / 2 + origin.x, visibleSize.height / 2 + origin.y ) );
listView->setTouchEnabled( true );
listView->setBounceEnabled( true );
// option
listView->setBackGroundImage( "Background image filepath" );
// add a UI element to the list view
listView->pushBackCustomItem( customItem );
var listView = new ccui.ListView( );
// scrol direction (ccui.ScrollView.DIR_VERTICAL or ccui.ScrollView.DIR_HORIZONTAL)
listView.setDirection( ccui.ScrollView.DIR_VERTICAL );
listView.setTouchEnabled( true );
listView.setBounceEnabled( true );
// optional
listView.setBackGroundImage( "Background image filepath" );
// add a UI element to the list view
listView.pushBackCustomItem( customItem );
To detect when the user interacts with the list view a touch event listener needs to be attached to it.
void selectedItemEvent( Ref *sender, ListView::EventType type );
// this is used to assign the touch event listener (usually is coded when the list view is constructed)
listView->addEventListener( CC_CALLBACK_2( ClassName::selectedItemEvent, this ) );
// this is called when the user interacts with the list view
void ClassName::selectedItemEvent( Ref *sender, ui::ListView::EventType type )
{
ui::ListView *listView = static_cast<ui::ListView *>( sender );
switch ( type )
{
case ui::ListView::EventType::ON_SELECTED_ITEM_START:
log( "select child start index = %ld", listView->getCurSelectedIndex( ) );
break;
case ui::ListView::EventType::ON_SELECTED_ITEM_END:
log( "select child end index = %ld", listView->getCurSelectedIndex( ) );
break;
default:
break;
}
}
// this is used to assign the touch event listener (usually is coded when the list view is constructed)
listView.addEventListener(this.selectedItemEvent, this);
// this is called when the user interacts with the list view
selectedItemEvent: function ( sender, type )
{
switch ( type )
{
case ccui.ListView.EVENT_SELECTED_ITEM:
cc.log( "select child index = " + sender.getCurSelectedIndex( ) );
break;
default:
break;
}
}
UILoadingBar - a UI element used to visualise the progress of a operation inside the game
LoadingBar *loadingBar = LoadingBar::create( "Loading bar image filepath" );
// set the increment of the loading bar (ranges from 0 - 100)
loadingBar->setPercent( 0 );
var loadingBar = new ccui.LoadingBar( );
loadingBar.loadTexture( "Loading bar image filepath" );
// set the increment of the loading bar (ranges from 0 - 100)
loadingBar.setPercent( 0 );
Note: Cocos handles the incrementation, so the texture that is set just needs to be the bar fully loaded
UIPageView - allows the user to scroll through different pages (layouts)
PageView *pageView = PageView::create( );
pageView->setTouchEnabled( true );
pageView->setContentSize( Size( 240.0, 900.0 ) );
pageView->setAnchorPoint( Vec2( 0.5, 0.5 ) );
Layout *layout = Layout::create( );
layout->setContentSize( Size( 240.0, 900.0 ) );
// add a node to the layout (multiple nodes can be added to the layout)
layout->addChild( elementToAddToLayout );
// add a layout as a page
pageView->addPage( layout );
// add a layout as a page at a certain index
pageView->insertPage( layout, 1 );
// remove a particular page
pageView->removePageAtIndex( 0 );
// remove all the pages
pageView->removeAllPages( );
// scroll to a particular page
pageView->scrollToPage( 2 );
var pageView = new ccui.PageView( );
pageView.setTouchEnabled( true );
pageView.setContentSize( cc.size( 240.0, 900.0 ) );
pageView.setAnchorPoint( cc.p( 0.5, 0.5 ) );
var layout = new ccui.Layout( );
layout.setContentSize( cc.size( 240.0, 900.0 ) );
// add a node to the layout (multiple nodes can be added to the layout)
layout.addChild( elementToAddToLayout );
// add a layout as a page
pageView.addPage( layout );
// add a layout as a page at a certain index
pageView.insertPage( layout, 1 );
// remove a particular page
pageView.removePageAtIndex( 0 );
// remove all the pages
pageView.removeAllPages( );
// scroll to a particular page
pageView.scrollToPage( 2 );
Note: Each layout corresponds to a page in the pageview
To detect when the user interacts with the page view a touch event listener needs to be attached to it.
void pageViewEvent( Ref *sender, PageView::EventType type );
// this is used to assign the touch event listener (usually is coded when the page view is constructed)
pageView->addEventListener( CC_CALLBACK_2( ClassName::pageViewEvent, this ) );
// this is called when the user interacts with the page view
void ClassName::pageViewEvent( Ref *sender, PageView::EventType type )
{
switch ( type )
{
case PageView::EventType::TURNING:
PageView *pageView = dynamic_cast<PageView *>( sender );
CCLOG( "%i", pageView->getCurPageIndex( ) );
break;
default:
break;
}
}
// this is used to assign the touch event listener (usually is coded when the page view is constructed)
pageView.addEventListener( this.pageViewEvent, this );
// this is called when the user interacts with the page view
pageViewEvent: function ( sender, type )
{
switch ( type )
{
case ccui.PageView.EVENT_TURNING:
var pageView = sender;
cc.log( "Current page " + pageView.getCurPageIndex( ) );
break;
default:
break;
}
}
UIRichText - a UI text element which is comprised of several rich text items. Each item has it's own properties such as colour and size
Example format:
RichTextItem( stringID, colour, alpha, stringToDisplay, fontToUse );
RichText *richText = RichText::create( );
// sets whether or not the element resizes based on its content aka rich text items added below
richText->ignoreContentAdaptWithSize( false );
richText->setContentSize( Size( 120, 100 ) );
RichElementText *re1 = RichElementText::create( 1, Color3B::WHITE, 255, "This color is white", "Font filepath", 10 );
RichElementText *re2 = RichElementText::create( 2, Color3B::YELLOW, 255, "And this is yellow. ", "Font filepath", 10 );
RichElementText *re3 = RichElementText::create( 3, Color3B::BLUE, 255, "This one is blue. ", "Font filepath", 10 );
RichElementText *re4 = RichElementText::create( 4, Color3B::GREEN, 255, "And this is Green. ", "Font filepath", 25 );
RichElementText *re5 = RichElementText::create( 5, Color3B::RED, 255, "This is well red . ", "Font filepath", 10 );
RichElementText *re6 = RichElementText::create( 6, Color3B::ORANGE, 255, "WELL DONE AT THE END. ", "Font filepath", 10 );
// add all the rich text items
richText->pushBackElement( re1 );
richText->pushBackElement( re2 );
richText->pushBackElement( re3 );
richText->pushBackElement( re4 );
richText->pushBackElement( re5 );
// insert the element at a particular index
richText->insertElement( re6, 5 );
var richText = new ccui.RichText( );
// sets whether or not the element resizes based on its content aka rich text items added below
richText.ignoreContentAdaptWithSize( false );
richText.width = 120;
richText.height = 100;
var re1 = new ccui.RichElementText( 1, cc.color.WHITE, 255, "This color is white", "Font filepath", 10 );
var re2 = new ccui.RichElementText( 2, cc.color.YELLOW, 255, "And this is yellow. ", "Font filepath", 10 );
var re3 = new ccui.RichElementText( 3, cc.color.BLUE, 255, "This one is blue. ", "Font filepath", 10 );
var re4 = new ccui.RichElementText( 4, cc.color.GREEN, 255, "And this is Green. ", "Font filepath", 25 );
var re5 = new ccui.RichElementText( 5, cc.color.RED, 255, "This is well red . ", "Font filepath", 10 );
var re6 = new ccui.RichElementText( 6, cc.color.ORANGE, 255, "WELL DONE AT THE END. ", "Font filepath", 10 );
// add all the rich text items
richText.pushBackElement( re1 );
richText.pushBackElement( re2 );
richText.pushBackElement( re3 );
richText.pushBackElement( re4 );
richText.pushBackElement( re5 );
// insert the element at a particular index
richText.insertElement( re6, 5 );
UIScrollView - scroll through nodes
ui::ScrollView *scrollView = ui::ScrollView::create( );
scrollView->setDirection( ui::ScrollView::Direction::VERTICAL );
scrollView->setContentSize( Size( 300, 200 ) );
scrollView->setInnerContainerSize( Size( 1280, 2500 ) );
scrollView->setBackGroundImage( "HelloWorld.png" );
scrollView->setBounceEnabled( true );
scrollView->setAnchorPoint( Vec2( 0.5, 0.5 ) );
scrollView->setPosition( Vec2( visibleSize.width / 2 + origin.x, visibleSize.height / 2 + origin.y) );
for ( int i = 0; i < 50; i++ )
{
ui::Button *button = ui::Button::create( "CloseNormal.png", "CloseSelected.png" );
button->setPosition( Vec2( scrollView->getContentSize( ).width / 2, i * 50 ) );
scrollView->addChild( button );
}
this->addChild( scrollView );
var scrollView = new ccui.ScrollView( );
// ccui.ScrollView.DIR_VERTICAL or ccui.ScrollView.DIR_HORIZONTAL
scrollView.setDirection( ccui.ScrollView.DIR_VERTICAL );
scrollView.setTouchEnabled( true );
scrollView.setBounceEnabled( true );
// optional
scrollView.setBackGroundImage( "Background image filepath" );
// visible scroll view size
scrollView.setContentSize( cc.size( 300, 200 ) );
// total scroll view size
scrollView.setInnerContainerSize( cc.size( 1280, 2500 ) );
scrollView.setAnchorPoint( cc.p( 0.5, 0.5 ) );
// add a node to the scroll view
scrollView.addChild( nodeToAdd );
Note: ScrollView requires the namespaceui:: otherwise it is ambiguous
UISlider - slider to control a variable
Slider *slider = Slider::create( );
slider->setTouchEnabled( true );
slider->loadBarTexture( "Slider background filepath" );
slider->loadSlidBallTextures( "Slider button filepath", "Slider button clicked filepath", "" );
slider->loadProgressBarTexture( "Progress bar filepath" );
var slider = new ccui.Slider( );
slider.setTouchEnabled( true );
slider.loadBarTexture( "Slider background" );
slider.loadSlidBallTextures( "Slider button", "Slider button clicked", "" );
slider.loadProgressBarTexture( "Progress bar" );
To detect when the user interacts with the slider a touch event listener needs to be attached to it.
void sliderEvent( Ref *sender, Slider::EventType type );
// this is used to assign the touch event listener (usually is coded when the slider is constructed)
slider->addEventListener( CC_CALLBACK_2( ClassName::sliderEvent, this ) );
// this is called when the user interacts with the slider
void ClassName::sliderEvent( Ref *sender, Slider::EventType type )
{
if (type == Slider::EventType::ON_PERCENTAGE_CHANGED)
{
Slider* slider = dynamic_cast<Slider*>( sender );
int percent = slider->getPercent( );
CCLOG( "%i", percent );
}
}
// this is used to assign the touch event listener (usually is coded when the slider is constructed)
slider.addEventListener( this.sliderEvent, this );
// this is called when the user interacts with the slider
sliderEvent: function( sender, type )
{
switch (type)
{
case ccui.Slider.EVENT_PERCENT_CHANGED:
cc.log("Percent " + sender.getPercent().toFixed(0));
break;
}
}
UIText - a simple text element
// the final parameter is the font size
Text *text = Text::create( "String to display", "Font filepath", 32 );
text->ignoreContentAdaptWithSize( false );
// TextHAlignment::LEFT, TextHAlignment::CENTER or TextHAlignment::RIGHT
text->setTextHorizontalAlignment( TextHAlignment::CENTER );
// TextVAlignment::LEFT, TextVAlignment::CENTER or TextVAlignment::RIGHT
text->setTextVerticalAlignment( TextVAlignment::CENTER );
text->setTouchScaleChangeEnabled( true );
text->setTouchEnabled( true );
var text = new ccui.Text( );
text.setString( "String to display" );
text.setFontName( "Font filepath" );
text.setFontSize( 32 );
// cc.TEXT_ALIGNMENT_LEFT, cc.TEXT_ALIGNMENT_CENTER or cc.TEXT_ALIGNMENT_RIGHT
text.setTextHorizontalAlignment( cc.TEXT_ALIGNMENT_CENTER );
// cc.VERTICAL_TEXT_ALIGNMENT_LEFT, cc.VERTICAL_TEXT_ALIGNMENT_CENTER or cc.VERTICAL_TEXT_ALIGNMENT_RIGHT
text.setTextVerticalAlignment( cc.VERTICAL_TEXT_ALIGNMENT_CENTER );
UITextAtlas - an atlas text string
Example format:
Text( stringToDisplay, characterMapToUse, characterWidth, characterHeight, startingCharacterInTheMap );
TextAtlas *text = TextAtlas::create( "String to display", "Character map filepath", 5, 5, "2" );
var textAtlas = new ccui.TextAtlas( );
textAtlas.setProperty( "String to display", "Character map filepath", 5, 5, "2" );
Note: *Glypth Designer can be used to create BMFonts https://71squared.com/en/glyphdesigner
UITextBMFont - an BM Font text string
TextBMFont *text = TextBMFont::create( "String to display", "Bitmap font filepath" );
var labelBMFont = new ccui.TextBMFont( );
labelBMFont.setFntFile( "Bitmap font filepath" );
labelBMFont.setString( "String to display" );
Note: *Glypth Designer can be used to create BMFonts https://71squared.com/en/glyphdesigner
UITextField - provides a means for text input for the user
// the final parameter is the font size
TextField *textField = TextField::create( "Input text here","Font filepath", 30 );
textField->setTouchEnabled( true );
// optional length functions
textField->setMaxLengthEnabled( true );
textField->setMaxLength( 12 );
// optional password character mask functions
textField->setPasswordEnabled( true );
textField->setPasswordStyleText( "*" );
var textField = new ccui.TextField( );
textField.setTouchEnabled( true );
textField.fontName = "Font filepath";
textField.placeHolder = "Input text here";
textField.fontSize = 30;
// optional length functions
textField.setMaxLengthEnabled( true );
textField.setMaxLength( 12 );
// optional password character mask functions
textField.setPasswordEnabled( true );
textField.setPasswordStyleText( "*" );
To detect when the user interacts with the text field a touch event listener needs to be attached to it.
void textFieldEvent( Ref *sender, ui::TextField::EventType type );
// this is used to assign the touch event listener (usually is coded when the text field is constructed)
textField->addEventListener( CC_CALLBACK_2( ClassName::textFieldEvent, this ) );
// this is called when the user interacts with the text field
void ClassName::textFieldEvent( Ref *sender, ui::TextField::EventType type )
{
ui::TextField* textField = dynamic_cast<ui::TextField *>( sender );
switch (type)
{
// keyboard is activated
case ui::TextField::EventType::ATTACH_WITH_IME:
log( "Keyboard opened" );
break;
// keyboard is deactivated
case ui::TextField::EventType::DETACH_WITH_IME:
log( "Keyboard closed" );
break;
// character insertion
case ui::TextField::EventType::INSERT_TEXT:
log( "%s", textField->getString( ).c_str() );
break;
// character deletion
case ui::TextField::EventType::DELETE_BACKWARD:
log( "%s", textField->getString( ).c_str( ) );
break;
default:
break;
}
}
// this is used to assign the touch event listener (usually is coded when the text field is constructed)
textField.addEventListener( this.textFieldEvent, this );
// this is called when the user interacts with the text field
textFieldEvent: function( sender, type )
{
switch ( type )
{
// keyboard is activated
case ccui.TextField.EVENT_ATTACH_WITH_IME:
break;
// keyboard is deactivated
case ccui.TextField.EVENT_DETACH_WITH_IME:
break;
// character insertion
case ccui.TextField.EVENT_INSERT_TEXT:
cc.log( "%s", textField.string );
break;
// character deletion
case ccui.TextField.EVENT_DELETE_BACKWARD:
cc.log( "%s", textField.string );
break;
}
}
UIVideoPlayer - provides a means for playing videos
experimental::ui::VideoPlayer *videoPlayer = experimental::ui::VideoPlayer::create( );
videoPlayer->setURL( "Video Url" );
videoPlayer->setContentSize( Size( visibleSize.width,visibleSize.height ) );
videoPlayer->play( );
videoPlayer->setPosition( Vec2( visibleSize.width / 2 + origin.x, visibleSize.height / 2 + origin.y ) );
videoPlayer->setFullScreenEnabled( true );
this->addChild( videoPlayer );
To detect different state changes for the video play such as playing and pausing an event listener needs to be attached to it.
void videoEventCallback( cocos2d::Ref *sender, cocos2d::experimental::ui::VideoPlayer::EventType eventType );
// this is used to assign the event listener (usually is coded when the video player is constructed)
videoPlayer->addEventListener( CC_CALLBACK_2( ClassName::videoEventCallback, this ) );
// this is called when the video player state changes
void ClassName::videoEventCallback(Ref* sender, experimental::ui::VideoPlayer::EventType eventType)
{
switch ( eventType )
{
case experimental::ui::VideoPlayer::EventType::PLAYING:
log( "Playing" );
break;
case experimental::ui::VideoPlayer::EventType::PAUSED:
log( "Paused" );
break;
case experimental::ui::VideoPlayer::EventType::STOPPED:
log( "Stopped" );
break;
case experimental::ui::VideoPlayer::EventType::COMPLETED:
log( "Completed" );
break;
default:
break;
}
}
UIWebView - provides a means for displaying web pages
experimental::ui::WebView *webView = experimental::ui::WebView::create( );
webView->setPosition( visibleSize / 2 );
webView->setContentSize( visibleSize * 0.8 );
webView->loadURL( "http://www.google.co.uk" );
webView->setScalesPageToFit( true );
webView->reload( );
webView->goBack( );
webView->goForward( );
this->addChild( webView );
To detect if the page as loaded or not listeners can be attached to the UIWebView.
bool onWebViewShouldStartLoading( cocos2d::experimental::ui::WebView *sender, const std::string &url );
void onWebViewDidFinishLoading( cocos2d::experimental::ui::WebView *sender, const std::string &url );
void onWebViewDidFailLoading( cocos2d::experimental::ui::WebView *sender, const std::string &url );
// this is used to assign the listeners (usually is coded when the web view is constructed)
webView->setOnDidFailLoading( CC_CALLBACK_2( ClassName::onWebViewDidFailLoading, this ) );
webView->setOnShouldStartLoading( CC_CALLBACK_2( ClassName::onWebViewShouldStartLoading, this ) );
webView->setOnDidFinishLoading( CC_CALLBACK_2( ClassName::onWebViewDidFinishLoading, this ) );
bool ClassName::onWebViewShouldStartLoading( experimental::ui::WebView *sender, const std::string &url )
{
log( "Started Loading, url is %s", url.c_str( ) );
return true;
}
void ClassName::onWebViewDidFinishLoading( experimental::ui::WebView *sender, const std::string &url )
{
log( "Finished Loading, url is %s", url.c_str( ) );
}
void ClassName::onWebViewDidFailLoading( experimental::ui::WebView *sender, const std::string &url )
{
log( "Failed Loading, url is %s", url.c_str( ) );
}
Updated 4 months ago