首页 > 解决方案 > javafx 中如何将背景大小调整到窗口大小?

问题描述

我试图将背景大小设为窗口大小。但是,它很挑剔。我没有使用css文件格式。

它是实现窗口的主要部分。

public void start(Stage primaryStage) throws Exception {
    GameLoopManager loop = GameLoopManager.instance();
    Controller controller = new Controller(loop, primaryStage);
    loop.start(new MenuState());
    primaryStage.show();

    primaryStage.setFullScreen(true);


}

这是实现背景和舞台的身体部位。

private UISubScene optionSubScene;
private UISubScene helpSubScene;
private UISubScene creditsSubScene;
private UISubScene buttonChooserScene;

private UISubScene sceneToHide;

List<UIButton> menuButtons;

List<ButtonPicker> buttonsList;

private BUTTON chosenButton;

public MenuViewManager(Stage mainStage) {
    sound.backgroundMusic();
    menuButtons = new ArrayList<>();
    mainPane = new AnchorPane();
    mainScene = new Scene(mainPane);
    mainScene.setFill(null);
    mainStage.setScene(mainScene);

    super.mainStage = mainStage;

    createSubScenes();
    createButtons();
    createBackground();
    createLogo();

    super.mainStage.setOnCloseRequest(new EventHandler<WindowEvent>() {
        public void handle(WindowEvent we) {
            controller.stop();
        }
    });
    // mainStage.show();

}

private void createBackground() {
    Image backgroundImgae = new Image("main/resources/images/jxoPOUxa.gif",true);
    BackgroundImage background = new BackgroundImage(backgroundImgae, BackgroundRepeat.NO_REPEAT,
            BackgroundRepeat.NO_REPEAT, BackgroundPosition.DEFAULT, BackgroundSize.DEFAULT);        
    mainPane.setBackground(new Background(background));


}

我厌倦了使用 BackgroundSize.AUTO 但是,我不能。我应该怎么做才能得到解决方案?

如果,我可以用css格式怎么用呢?但是我不能重写和修改很多代码,因为我的代码快完成了,我正在集成和调试。

标签: javaeclipsejavafx

解决方案


如果要拉伸图像以填充整个图像,Region则应使用:

// Side note: Are you sure having "main/resources" in the path is correct?
var image = new Image("main/resources/images/jxoPOUxa.gif", true);
var bgImage = new BackgroundImage(
        image,
        BackgroundRepeat.NO_REPEAT,
        BackgroundRepeat.NO_REPEAT,
        BackgroundPosition.DEFAULT,
        new BackgroundSize(1.0, 1.0, true, true, false, false)
);
mainPain.setBackground(new Background(bgImage));

mean the和arguments的两个true参数分别是成比例的而不是绝对的。在这种情况下,and应该在范围内,也就是 0% 到 100%。这两个参数分别是和。它们必须是要使用的and参数。换句话说,这告诉 JavaFX 让图像填充. 请注意,这不会保持图像的纵横比(见下文)。BackgroundSizewidthheightwidthheight[0.0, 1.0]falsecontaincoverfalsewidthheightRegion

有关更多信息,请参阅文档BackgroundSize

定义 BackgroundImage 应填充的区域相对于其样式设置的区域的大小。有几个属性的值优先于其他属性。特别是有 4 个关键属性,widthheightcontaincover。宽度和高度都相互独立,但都与包含和覆盖交互。

从 CSS 规范中,cover定义为:

  • 缩放图像,同时保留其固有纵横比(如果有),使其宽度和高度都可以完全覆盖背景定位区域。

contain定义为:

  • 将图像缩放到最大尺寸,同时保留其固有纵横比(如果有),使其宽度和高度都可以适合背景定位区域。

宽度和高度都指定(以绝对值或百分比形式)要使用的大小。这两个属性仅适用于覆盖和包含都为假的情况。如果cover 和contain 都为真,那么将使用cover。

宽度和高度也可以设置为AUTO,表示应调整区域大小以使用图像的固有大小,或者如果无法确定,则为 100%。


推荐阅读