【问题标题】:javafx stretch an image to fill a button?javafx拉伸图像以填充按钮?
【发布时间】:2018-06-04 18:01:19
【问题描述】:

我正在编写一个“星际迷航”游戏,以获得 Java/JavaFX 的乐趣。我的想法是主游戏屏幕是一个 10x10 的 GridPane 按钮。所有游戏部件(企业号、克林贡人、行星等)都将在按钮中显示为图标。这样,您可以单击一个空间对象来选择它、变形到它、射击它等等:

当然,这一切都取决于能否将我的小星舰图像分配给适当的按钮。我已经想出了如何将背景应用到按钮,但是当我应用图像时,合身并不好。这是迄今为止我的游戏截图:

“企业”形象有点适合……但不是真的。必须有一种方法可以拉伸船以适应按钮完全,但我还没有找到它。我还必须找到一种在 Java(不是 CSS 或 FXML)中执行此操作的方法,因为 Java 代码必须移动图标。

这是我的代码:

public void setUpBoard(){

  // set up 10x10 GridPane of Buttons...

  Image testImage = new Image(getClass().getResourceAsStream("Enterprise.png"));
  ImageView testImageView = new ImageView(testImage);
  testImageView.setFitWidth(55);            // My button is 55 x 37 pixels, according to the FXML
  testImageView.setFitHeight(37);
  //testImageView.fitWidthProperty().bind(gridButton37.widthProperty());   // This didn't work either
  //testImageView.fitHeightProperty().bind(gridButton37.widthProperty());
  gridButton37.setGraphic(testImageView);
}

我已经用谷歌搜索了几个小时,但我找不到似乎适用于此的“将图像拉伸到父级”解决方案。有什么我遗漏的吗?

【问题讨论】:

  • 在我看来你没有。使用带有适当参数的BackgroundImage 作为Background 的一部分(see background property) 允许您将图像拉伸到指定大小。或者,您可以在加载或使用fitWidth/fitHeight 时为Image 指定适当的大小,并且不要使用ImageView 保留纵横比...

标签: image button javafx


【解决方案1】:
    btnTest.setMinSize(55, 37);
    btnTest.setMaxSize(55, 37);

    Image image = new Image("/view/images/someImage.png", btnTest.getWidth(), btnTest.getHeight(), false, true, true);
    BackgroundImage bImage = new BackgroundImage(image, BackgroundRepeat.NO_REPEAT, BackgroundRepeat.NO_REPEAT, BackgroundPosition.CENTER, new BackgroundSize(btnTest.getWidth(), btnTest.getHeight(), true, true, true, false));

    Background backGround = new Background(bImage);
    btnTest.setBackground(backGround);

见https://docs.oracle.com/javase/8/javafx/api/javafx/scene/layout/Background.html

【讨论】:

  • 另外,如果我可以建议,您可以将背景实现为枚举(因为,您必须根据您的游戏规则将这些设置为不同的按钮)。
  • -- 谢谢,成功了。我已经阅读(真的:略读)您提供的文档,但老实说,我没有看到如何将它直接应用于我的情况。有时,一点帮助会非常有用。 :)
猜你喜欢
  • 1970-01-01
  • 2016-01-06
  • 2011-07-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-02
  • 2015-11-19
  • 1970-01-01
相关资源
最近更新 更多