aran aran - 4 months ago 44
Java Question

Scaling an ImageView to a specific height in JavaFX

I have an

Imageview
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
ImageView
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.setFitHeight(40);
mapPreview.setOnMouseClicked(event -> System.out.println("towerChooserPopup should open now!"));
} catch (MalformedURLException | URISyntaxException e) {
e.printStackTrace();
}
HBox mapChooserWrapper = new HBox(mapChooserLabel, mapPreview);
mapChooserWrapper.setId("lineWrapper");


And here is my css:

#lineWrapper{
-fx-alignment: center;
-fx-spacing: 2px;
}

Answer

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:

mapPreview.setFitHeight(40);
mapPreview.setPreserveRatio(true);

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.

Comments