UI Text widget location problem

Hello.

void LoginRegisterScene::MessageBoxDreals(const char* msg, const char* title){
    Size visibleSize = Director::getInstance()->getVisibleSize();
    Vec2 origin = Director::getInstance()->getVisibleOrigin();

    this->bgMessageBox = Sprite::create("res/DialogBox/bg_alert.png");
    this->bgMessageBox->setPosition(visibleSize.width / 2 + origin.x, visibleSize.height / 2 + origin.y);
    this->addChild(this->bgMessageBox, 3);

    this->lblMsgMessageBox = cocos2d::ui::Text::create("asdajdhajgdamh sadg asmhda dsahs dah dahsgdakshdgakdsgaksd a","AmericanTypewriter",13);
    this->lblMsgMessageBox->setColor(Color3B::BLACK);
    this->lblMsgMessageBox->ignoreContentAdaptWithSize(false);
    this->lblMsgMessageBox->setContentSize(Size(280, 150));
    this->lblMsgMessageBox->setTextHorizontalAlignment(TextHAlignment::CENTER);
    this->lblMsgMessageBox->setTextVerticalAlignment(TextVAlignment::CENTER);
    //titleLabel->setPosition(Vec2(widgetSize.width / 2.0f, widgetSize.height / 2.0f - text->getContentSize().height / 8.0f));
    this->lblMsgMessageBox->setPosition(Vec2(visibleSize.width / 2 + origin.x, visibleSize.height / 2 + origin.y));
    this->bgMessageBox->addChild(this->lblMsgMessageBox);
}

I’m trying to add a text widget as child to a sprite. As can be seen, i’m trying to set a custom messagebox. The problem is, text won’t be located in the middle of the sprite. Can anybody help me with this?

To centre the text in the sprite you need to use the sprite’s dimensions not the screen’s.

Change:

this->lblMsgMessageBox->setPosition(Vec2(visibleSize.width / 2 + origin.x, visibleSize.height / 2 + origin.y));

To:

auto spriteSize  = this->bgMessageBox->getContentSize();
this->lblMsgMessageBox->setPosition(Vec2(spriteSize.width * 0.5f, spriteSize.height * 0.5f));

Hope this helps

It works absolutely :smile: Thank you.