GameCorder.net

このエントリーをはてなブックマークに追加

About label in Cocos2dx

Lable is ui tool in cocos2dx.
simply show text in system font
let's see the example


// import ui
#include "ui/CocosGUI.h"

// 1.create label
Label* textLabel = Label::createWithTTF("submit score?","fonts/arial.ttf",36);
textLabel->setAnchorPoint(Vec2::ZERO);
textLabel->setPosition(Vec2(100,100));
// text color
textLabel->setTextColor(Color4B(0,0,0,255));
// 2.set text string if want to change
textLabel->setString("example");
// add ui to show
this->addChild(textLabel);
		

1.create Label

In this case Use Label::createWithTTF()
crete label with ttf extention.
function detail is


/**
* Allocates and initializes a Label, base on FreeType2.
*
* @param text The initial text.
* @param fontFilePath A font file.
* @param fontSize The font size. This value must be > 0.
* @param dimensions
* @param hAlignment The text horizontal alignment.
* @param vAlignment The text vertical alignment.
*
* @return An automatically released Label object.
*/
static Label * createWithTTF(const std::string& text, const std::string& fontFilePath, float fontSize,
    const Size& dimensions = Size::ZERO, TextHAlignment hAlignment = TextHAlignment::LEFT,
    TextVAlignment vAlignment = TextVAlignment::TOP);
	

Set label Alignment

let's learn how to align in label.
Firstly define dimentions in label.


Label* textLabel = Label::createWithTTF("submit score?","fonts/arial.ttf",36);
textLabel->setDimensions(WIDTH,HEIGHT);
// set alignment
textLabel->setAlignment(TextHAlignment::CENTER, TextVAlignment::CENTER);
		

Of cource width and height is Size of contents to display.
and call setAlignment function.
function is...


/** Sets the Label's text horizontal alignment.*/
void setAlignment(TextHAlignment hAlignment) { setAlignment(hAlignment,_vAlignment);}
		

If want to align left or right jump constant values.
like from TextHAlignment::CENTER.

another approach to align text

another approach to describe label in center.
calculate center position and put center.

To get content size

To get content size,use getContentSize().


Label* textLabel = Label::createWithTTF("submit score?","fonts/arial.ttf",36);
int width = textLabel->getContentSize().width;
int height = textLabel->getContentSize().height;
// set center
textLabel->setPosition(Vec2((WIDTH / 2) - (width / 2) ,HEIGHT - height));
		

In this example get size of label and put center use setPosition()

This is available in cocos2dx 3.15.1