首页 > 解决方案 > JFX 将图像向上和向下缩放到父级

问题描述

我正在尝试拥有一个与其父级一起缩放的 ImageView。我已经搜索了我可以找到的所有 StackOverflow 帖子,这是我尝试过的:

        taggedImage.setPreserveRatio(true);
    //taggedImage.fitWidthProperty().bind(
    //      Bindings.min(imagePane.widthProperty(), imagePane.widthProperty()));
    //taggedImage.fitHeightProperty().bind(
    //      Bindings.min(imagePane.heightProperty(), imagePane.heightProperty()));
    taggedImage.fitWidthProperty().bind(imagePane.widthProperty());
    taggedImage.fitHeightProperty().bind(imagePane.heightProperty());

我也尝试过的注释行以及这些方法的问题是,当 imageview 绑定到父级时,父级只能放大而不能缩小。因此,如果增加窗口的大小,图片会变大。如果再次减小图片大小,则不会减小图片大小。在此示例中,imagePane 是 StackPane。我也尝试过borderFrame。同样,我尝试使用窗格作为父级。这样,图像就可以成功地放大和缩小。但是,如果图像与窗格的大小不完全匹配,则图像不会居中并且始终位于窗格的左上角。

场景树: https ://gyazo.com/45e0daebbfd98dfd3446185d21eb91ee

价值观:

Top gridpane:
https://gyazo.com/f48ebb39f48d876a02d44792a73eaad4
lower level gridpane:
https://gyazo.com/3399d9f3ab00e8babd36ee3b0e3b27ba
BorderPane:
https://gyazo.com/51c24f8de50ae3865a299fdddf3a1490
ImageView:
https://gyazo.com/7dfc1071d2b516a83baed301596be2b9

请注意,我在这里尝试使用边框窗格而不是我以前使用的。但是,无论哪个对象是 imageview 的父对象,结果都是一样的。

标签: javauser-interfacejavafxjavafx-8

解决方案


解决了。我一直在搞乱,并找到了解决办法。这并不完全直观,但对我有用:我将图像留在了边框内,并且在 java 代码中,我在网格窗格的同一部分创建了一个窗格作为图像。然后我将图像视图的宽度和高度绑定到窗格。然后,图像的居中以及缩放都是正确的。这是我所做的:

    imageView.setPreserveRatio(true);
    Pane pane = new Pane();
    testGridPane.add(pane, 1, 1);
    imageView.fitWidthProperty().bind(pane.widthProperty());
    imageView.fitHeightProperty().bind(pane.heightProperty());

推荐阅读