【发布时间】: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的一部分(seebackgroundproperty) 允许您将图像拉伸到指定大小。或者,您可以在加载或使用fitWidth/fitHeight时为Image指定适当的大小,并且不要使用ImageView保留纵横比...