afghg
afghg

Reputation: 33

JavaFX down-size ImageView

I have a group which contains a rectangle and an image on top. I want the rectangle to be re-sizable and the image should have a fixed size except for the case when the rectangle is smaller than the image. Then the image should down-size with the rectangle.

The image should also always be centered and have some padding.

I have most of these parts done, except the down-sizing part of the image. I don't know why, but the image will not down-size at all. This is what I've got.

    Group group = new Group()
    GeometryNode<Rectangle> rectangle = new GeometryNode<>();
    rectangle.setGeometry(new Rectangle(0, 0, 60, 60));

    ImageView imageView = new ImageView(image);
    imageView.setPreserveRatio(true);

    ImageViewPane imagePane = new ImageViewPane(imageView);
    imagePane.setMinSize(0, 0);
    imagePane.setMaxSize(50, 50);

    StackPane stackPane = new StackPane();

    stackPane.getChildren().add(rectangle);
    stackPane.getChildren().add(imagePane);
    group.getChildren().add(stackPane);

Upvotes: 1

Views: 103

Answers (1)

James_D
James_D

Reputation: 209684

You want the fitWidth and fitHeight properties of the ImageView to change if the dimensions of the StackPane change. So you can do

double padding = ... ;

imageView.setPreserveRatio(true);
imageView.fitWidthProperty().bind(
    Bindings.min(stackPane.widthProperty().subtract(padding), image.widthProperty()));
imageView.fitHeightProperty().bind(
    Bindings.min(stackPane.heightProperty().subtract(padding), image.heightProperty()));

Upvotes: 1

Related Questions