LibGDX how to make a buttons size independent of image

Anything libgdx related goes here!

LibGDX how to make a buttons size independent of image

Postby katherineamt » Wed Nov 14, 2018 1:35 pm

When adding images to a TextButton in LibGDX how would I match the button to the contents of the image. Currently when I set size the image scales down to fit the button which leaves a large gap between the edge of the button and the contents of the image (See distance from green debug border to the edge of the buttons image).

I would like to be able to set the size of the button to match the content of the image so that the empty space around the image is ignored. I could crop out the empty space from the image but would have an off centered image due to the drop shadow and so would like to avoid that.

Top image shows the displayed dutton in game including the debug button border in green. Bottom image shows the source image with empty space.

Code: Select all
TextButton.TextButtonStyle buttonStyle = new TextButton.TextButtonStyle();
buttonStyle.font = FontLoader.uiFont;
buttonStyle.up = new SpriteDrawable(new Sprite(assetManager.get(UISpriteLoader.SPRITE_UI_TAMING_BUTTON_BASE, Texture.class)));
buttonStyle.down = new SpriteDrawable(new Sprite(assetManager.get(UISpriteLoader.SPRITE_UI_TAMING_BUTTON_PRESSED, Texture.class)));
buttonStyle.over = new SpriteDrawable(new Sprite(assetManager.get(UISpriteLoader.SPRITE_UI_TAMING_BUTTON_HOVER, Texture.class)));
tameButton = new TextButton("Tame", buttonStyle);
tameButton.setPosition(1470, 1080-330-80);
tameButton.setSize(250, 80);
Posts: 1
Joined: Wed Nov 14, 2018 12:49 pm

Re: LibGDX how to make a buttons size independent of image

Postby shatterblast » Wed Nov 14, 2018 5:17 pm

I am just throwing out an idea. As a work-around, you could have two different sizes of the same image, and thus, two different sizes of the same Button. You could set the width and height of the current Button to be relatively same to the width and height of the existing image. Just change the size of the Button when swapping one picture with a different one. You could use these instead of entering your own values in setSize() of tameButton :
Posts: 289
Joined: Sun Jul 06, 2014 1:14 pm

Re: LibGDX how to make a buttons size independent of image

Postby Androphin » Thu Nov 15, 2018 9:19 am

Why don't you use an ImageTextButton? ... utton.html

A button (and therefore its subclasses) is implementing the layout interface. So you can deal with a min, max and preferred size.
Posts: 35
Joined: Sun Aug 07, 2016 9:30 pm

Return to Libgdx

Who is online

Users browsing this forum: Exabot [Bot] and 1 guest