1

I have a Button with text and an ImageView as icon. The image might be of any resolution. Currently, the button will adapt its size to fit the image, e.g. if the image is 400x400, the button will be huge and the text will be tiny next to it.

What I want though, is the image to fit into the button. It should always be as tall as the text is.

ImageView img = new ImageView(image);
button = new Button("Some text", img);
button.setStyle("-fx-background-radius: 6em;");

Button with huge image and tiny text

piegames
  • 975
  • 12
  • 31

2 Answers2

1

Wouldn't have thought the solution to this is so easy:

img.setPreserveRatio(true);
img.setFitHeight(button.getFont().getSize());

does the trick for me. JavaFX is weirdly unintuitive sometimes. If the font size may change (e.g. via CSS styling), use a binding instead:

img.fitHeightProperty().bind(Bindings.createDoubleBinding(() -> button.getFont().getSize(), button.fontProperty()));
piegames
  • 975
  • 12
  • 31
0

You can set your image height via

image_view.getLayoutParams().height = YOURHEIGHT

as discussed here.

I would suggest setting your text size to an appropriate value and use the above command to scale the image to the same height.

Test around whether you can size the image with em, otherwise use cm/inch.

If there a problems with image distortion when setting height, refer to this thread.

  • 2
    Your answer is about Android, but the OP has tagged the question with [tag:javafx]. Note that both have an `ImageView` class. – Slaw Feb 21 '19 at 17:14