我有一个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/