java - 在 JavaFX 中将 ImageView 缩放到特定高度

标签 java javafx imageview scaling

我有一个Imageview在我的菜单中,显示了所选 map 的预览。

但是这些 map 的大小可能会有所不同,在我的菜单中我有足够的水平空间,但垂直方向上我有限制。所以,我想要的是缩放 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;
}

最佳答案

您可以使用setPreserveRatio 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

所以,在你的代码中:

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

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

关于java - 在 JavaFX 中将 ImageView 缩放到特定高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38271571/

相关文章:

java - 如何编写代码(按回车键时会显示下一个)java

java - 关闭组件内字段的乐观锁

android - 尝试绘制用户加载的位图

JavaFX 通过单击按钮更改文本

java - Android:保留设置为背景的 ImageView 的宽高比

android - 如何使用代码而不是xml设置ImageView的边距

java - JMS 应用程序给出错误

java - 我似乎无法让我的 fragment 在不崩溃的情况下加载 webview

java - 鼠标事件: the order of operations

java - 在 JavaFX 中获取屏幕上路径的 x y 坐标