【问题标题】:Scaling an ImageView to a specific height in JavaFX在 JavaFX 中将 ImageView 缩放到特定高度
【发布时间】:2016-07-08 16:32:16
【问题描述】:

我的菜单中有一个Imageview,它显示了所选地图的预览。

但是这些地图的大小可能会有所不同,在我的菜单中我有足够的水平空间,但在垂直方向上我有限制。所以,我想要的是缩放ImageView,使其高度变为 40 像素(我这里也有问题),并且宽度会相应地以不变形的方式发生变化。

如果有办法让高度自动适应它的线的高度,我会非常感激。(它的父级) 这是我的代码:

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");

这是我的 CSS:

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

【问题讨论】:

    标签: java javafx imageview scaling


    【解决方案1】:

    可以使用ImageViewsetPreserveRatio方法:

    表示是否保留源图片的纵横比 当缩放以适应拟合边界框内的图像时。

    如果设置为 true,它会影响这个 ImageView 在 以下方式*

    • 如果只设置了 fitWidth,则会缩放高度以保持比例
    • 如果只设置了 fitHeight,则会缩放宽度以保持比例
    • 如果两者都设置了,则它们都可以进行缩放,以在保持原始纵横比的情况下最适合宽高比的矩形

    所以,在你的代码中:

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

    或者您甚至可以使用 its constructor 在加载时调整 Image 的大小:

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

    但是在您的情况下,由于您想将其用作预览,因此以原始大小将其加载并存储图像参考更为合理,然后您可以在显示原始图像时使用它以避免重新加载图片。

    【讨论】:

    • 这根本没有帮助,因为他希望图像适合容器,因此图像必须具有自动大小,但没有选项
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-13
    • 2011-06-20
    相关资源
    最近更新 更多