aran aran - 1 year ago 89
Java Question

Scaling an ImageView to a specific height in JavaFX

I have an

in my menu which shows a preview of a chosen map.

But these maps can vary in size, in my menu I have enough horizontal space, but vertically I have limits. So, what I want is to scale the
in a way that its height becomes 40 pixels (I also have a problem here) and it's width change accordingly in a way that it does not deform.

Also I would appreciate it so much if there is a way to have the height automatically fit to the height of it's line.(its parent)
Here is my code:

Label mapChooserLabel = new Label("This is the map you will play on, click to change");
try {
mapPreview = new ImageView(
new Image(getClass().getResource("/files/images/maps/" + chosenMapName + ".gif").toURI().toURL().toString())
mapPreview.setOnMouseClicked(event -> System.out.println("towerChooserPopup should open now!"));
} catch (MalformedURLException | URISyntaxException e) {
HBox mapChooserWrapper = new HBox(mapChooserLabel, mapPreview);

And here is my css:

-fx-alignment: center;
-fx-spacing: 2px;

Answer Source

You can use the setPreserveRatio method of ImageView:

Indicates whether to preserve the aspect ratio of the source image when scaling to fit the image within the fitting bounding box.

If set to true, it affects the dimensions of this ImageView in the following way *

  • If only fitWidth is set, height is scaled to preserve ratio
  • If only fitHeight is set, width is scaled to preserve ratio
  • If both are set, they both may be scaled to get the best fit in a width by height rectangle while preserving the original aspect ratio

So, in your code:


Or you could even resize the Image on load using its constructor:

mapPreview = new ImageView(
    new Image(getClass().getResource("/files/images/maps/" + chosenMapName + ".gif").toURI().toURL().toString(), 
        40, 200, true, true));

But in your case, as you want to use this as a preview, it is more reasonable to load it in the original size and store the image reference, then you could use it when showing the original image to avoid the reloading of the image.