Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to center actors in a group with Scene2d and LibGDX?

I'm using LibGDX and Scene2d and I want to create a pop-up that looks like the one shown in the image below.

So far, I created a table and set the background to a semitransparent color. Then I created an image with a white background. This image expands x, so it is centered. Now I want to have a label centered inside the image. To overlay these two actors, I created a group, but I couldn't find out how to center something in a group. How can I do this?

scene2d example

Here is my code:

Table table = new Table();
table.top();
table.setFillParent(true);
table.setBackground(getColoredBackground(color));

labelStyle = new Label.LabelStyle(font, fontColor);
label = new Label(message, labelStyle);

Image image = new Image(whiteBackground);
image.setSize(table.getWidth() - padding, label.getHeight() + extraHeight);

Group group = new Group();
group.setSize(image.getWidth(), image.getHeight());

group.addActor(image);
group.addActor(label);
table.add(group).expandX().padTop(padTop);
like image 925
Antict Avatar asked Sep 14 '15 14:09

Antict


1 Answers

The group has it own coordinates system. It means that when you are setting actor position to (0,0) for example and then adding it to group which is actually at (100, 100) position then the object will be at (100, 100) position relative to the stage.

All you need to do is just to set:

    label.setPosition( group.getWidth() / 2f - label.getWidth() / 2f, group.getHeight() / 2f - label.getHeight() / 2f );

after setting Group size. Remember that setting actor's position we are defining its left bottom corner position and that's why you need to also subtract the half of label width/height.

Of course you can modify the y position it doesn't have to be centered vertically also

like image 168
m.antkowicz Avatar answered Nov 14 '22 21:11

m.antkowicz