简体   繁体   中英

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的例子

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);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM