【问题标题】:How to stretch a dynamically created background image in both directions in JavaFX如何在 JavaFX 中双向拉伸动态创建的背景图像
【发布时间】:2016-04-06 00:26:30
【问题描述】:

问题

我想在我的 JavaFX GUI 中设置背景图像。 GUI 应该可以调整到任何比例,这样我的背景图像必须在两个方向上拉伸(同时改变背景图像的宽度和高度之间的比例)

another stackoverflow post 启发,我通过 css 了解了如何做到这一点:

.root {
    -fx-background-image: url('http://icons.iconarchive.com/icons/iconka/meow/256/cat-box-icon.png');
    -fx-background-size: stretch;
}

但我有约束,我的背景图片是动态创建的作为BufferedImage

第一种方法

因此我开始通过代码而不是 css 设置我的背景图像,如下所示:

Region region = // ...
BufferedImage bufferedBackgroundImage = // ...
WritableImage fxImage = new WritableImage(bufferedBackgroundImage.getWidth(), bufferedBackgroundImage.getHeight());
SwingFXUtils.toFXImage(bufferedBackgroundImage, fxImage);

region.setBackground(
    new Background(
        new BackgroundImage(
            fxImage,
            BackgroundRepeat.NO_REPEAT,
            BackgroundRepeat.NO_REPEAT,
            BackgroundPosition.DEFAULT,
            new BackgroundSize(BackgroundSize.AUTO, BackgroundSize.AUTO, false, false, false, true))));

不幸的是,我的背景不再伸展了。 我在 BackgroundSize 和几个 BackgroundRepeat 常量中尝试了几种布尔值组合,但我只能在一个方向而不是两个方向上拉伸我的背景图像。

第二种方法

我尝试使用第一种方法的代码设置背景图像,然后添加样式表

region.setStyle("-fx-background-size: stretch;");

但随后背景图像完全消失了。我认为这是因为setStyle 而不是addStyle 所以我覆盖了它。

以下代码也不能正常工作。我认为是因为您只能将 URL 设置为 css 文件,但不能设置样式。

region.getStylesheets().add("-fx-background-size: stretch;");

问题

如果我能更进一步,我将不胜感激。

【问题讨论】:

    标签: java user-interface javafx-8


    【解决方案1】:

    我遇到了同样的问题,但后来发现可以使用 BackgroundFill 创建背景。因此,使用您的图像创建一个 BackgroundFill,然后使用它来创建背景。

    Region region = // ...
    
    Image image = new Image("/chart.png");
    BackgroundFill backgroundFill = new BackgroundFill(new ImagePattern(image), CornerRadii.EMPTY, Insets.EMPTY);
    region.setBackground(new Background(backgroundFill));
    

    【讨论】:

      猜你喜欢
      • 2011-11-12
      • 2010-12-09
      • 2017-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-28
      • 2015-07-26
      相关资源
      最近更新 更多