如果我理解正确,您的目标是:
- 保留图片的纵横比。
- 用图像覆盖整个区域(即任何一侧都没有间隙)。
我建议您将Region 的the background 设置为您的图像,而不是使用ImageView。然后,您可以将背景图像的the size 设置为cover,这将:
[...] 缩放图像,同时保留其固有纵横比(如果有),使其宽度和高度都可以完全覆盖背景定位区域。
可以通过编程、CSS 或 FXML 设置背景。
在 Java 中:
Image image = ...;
BackgroundImage bgImage = new BackgroundImage(
image, // image
BackgroundRepeat.NO_REPEAT, // repeatX
BackgroundRepeat.NO_REPEAT, // repeatY
BackgroundPosition.CENTER, // position
new BackgroundSize(-1, -1, false, false, false, true) // size
);
anchorPaneBackground.setBackground(new Background(bgImage));
在 CSS 中(参见JavaFX CSS Reference Guide):
/* Or whatever ID/style class you give the target region */
#achorPaneBackground {
-fx-background-image: url("your/image/path");
-fx-background-size: cover;
-fx-background-position: center;
-fx-background-repeat: no-repeat;
}
在 FXML 中(不能保证尽可能简洁):
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.image.Image?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.Background?>
<?import javafx.scene.layout.BackgroundImage?>
<?import javafx.scene.layout.BackgroundPosition?>
<?import javafx.scene.layout.BackgroundSize?>
<AnchorPane xmlns="http://javafx.com/javafx/12" xmlns:fx="http://javafx.com/fxml/1">
<background>
<Background>
<images>
<BackgroundImage repeatX="NO_REPEAT" repeatY="NO_REPEAT">
<image>
<Image url="your/image/path"/>
</image>
<position>
<BackgroundPosition fx:constant="CENTER"/>
</position>
<size>
<BackgroundSize cover="true"/>
</size>
</BackgroundImage>
</images>
</Background>
</background>
</AnchorPane>
注意:我不相信您可以在 Scene Builder 中设置 Region 的背景(添加样式表除外)。如果我错了,请纠正我。