How do I get an image in an ImageView to automatically resize such that it always fits the parent node?
Here is a small code example:
@Override
public void start(Stage stage) throws Exception {
BorderPane pane = new BorderPane();
ImageView img = new ImageView("http://...");
//didn't work for me:
//img.fitWidthProperty().bind(new SimpleDoubleProperty(stage.getWidth()));
pane.setCenter(img);
Scene scene = new Scene(pane);
stage.setScene(scene);
stage.show();
}
This is a better solution than binding the width property (better because often when binding a child to its container, it might not be possible to make the container smaller. At other ocasions the container might even automatically start growing).
The solution below relies on overriding an ImageView so that we can let it behave as 'resizable' and then providing implementations for the minimum ,preferred, and maximum width/heights. Also important is to actually implement the resize() call.
This is a calculated width method that removes the width of the scroll bar.
first:
myImageView.setPreserveRatio(true);
monitor scrollbar width changes:
scrollBar width:
oldValue.doubleValue() - scrollPane.getViewportBounds().getWidth()
How do I set init width?
after
primaryStage.show();
myImageView.setFitWidth(scrollPane.getViewportBounds().getWidth());
Use ScrollPane or simply Pane to overcome this problem: Example:
If you want the ImageView to fit inside a windows frame, use this line of code: imageView.fitWidthProperty().bind(scene.widthProperty()).
Note that I am using widthProperty of the scene not the stage. Example:
The aspect radio of the stage (primaryStage) should be similar to that of the image (1.2008.png)