What I want to do:
final ImageButtonStyle upStyle = new ImageButtonStyle();
upStyle.up = spriteUp;
upStyle.down = spriteDown;
upStyle.imageUp = spriteIcon;
imgButton = new ImageButton(upStyle);
imgButton.getImage().setScale(0.5f);
However, this produces the following result:
This is what I want:
In order to achieve this right now I have to call this code:
float scale = 0.5f;
imgButton.pack();
imgButton.getImage().setOrigin(imgButton.getImage().getWidth() * scale, imgButton.getImage().getHeight() * scale);
Things I've tried to play around with to no result (in no particular order):
imgButton.getImage().setAlign(Align.center);
imgButton.invalidate();
imgButton.pack();
imgButton.getImageCell().align(Align.center);
Any ideas, maybe some screwing around with the cell properties? Nothing seems to be changing anything unless I change the Origin manually and repack...
Thanks!
Try
imgButton.getImage().setOrigin(Align.center);
imgButton.getImage().setScale(0.5f);
Instead of doing the trick width width and height * 0.5f and using that as origin LibGDX has a nice way of specifying the center with Align.center.
Here's what worked in the end:
final ImageButtonStyle upStyle = new ImageButtonStyle();
upStyle.up = spriteUp;
upStyle.down = spriteDown;
upStyle.imageUp = spriteIcon;
imgButton = new ImageButton(upStyle);
final float scale = 0.5f;
imgButton.getImage().setScale(scale);
// Calling any of these works.
imgButton.pack();
imgButton.layout();
imgButton.validate();
// Calling these doesn't work.
imgButton.invalidate();
imgButton.invalidateHierarchy();
// Has to be called after either pack(), layout(), or validate() are called.
imgButton.getImage().setOrigin(Align.center);
stage = new Stage(new StretchViewport(500, 700));
stage.addActor(imgButton);
I don't understand why I have to call either of pack(), layout(), or validate() after setting the scale... But after trying many combinations I found this to work. Maybe someone could give some deeper insight on why this works the way it is and maybe if there's a better way?
Ideally what I would like to do is something like this:
final float scale = 0.5f;
imgButton.getImage().setScale(scale);
imgButton.getImage().setOrigin(Align.center);
// or
final float scale = 0.5f;
imgButton.getImage().setScale(scale);
imgButton.getImage().setOrigin(Align.center);
imgButton.pack(); // Forcing a pack / invalidate I can live with.
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.