javafx拉伸图像填充按钮? [英] javafx stretch an image to fill a button?

查看:875
本文介绍了javafx拉伸图像填充按钮?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Java / JavaFX编写一个星际迷航游戏。我的想法是主游戏画面是一个10x10的按钮GridPane。所有游戏部件(企业,克林贡人,行星等)都会在按钮中显示为图标。这样,您可以单击空间对象来选择它,扭曲它,拍摄它等等:

I am writing a "Star Trek" game for fun with Java/JavaFX. My idea is that the main game screen is an 10x10 GridPane of Buttons. All the game pieces (the Enterprise, Klingons, planets, etc) would appear as icons in the buttons. This way, you can click a space object to select it, warp to it, shoot it, etc:

当然,这完全取决于能否将我的小星舰图像分配到适当的按钮。我已经弄清楚如何将背景应用于按钮,但是当我应用图像时,合身效果并不理想。这是我到目前为止的游戏截图:

Of course, this is all contingent on being able to assign my little starship images to the appropriate buttons. I've figured out how to apply a background to a button, but when I apply the image, the fit is not good. Here's a screenshot of my game thus far:

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

The "Enterprise" image sorta fits... but not really. There's got to be a way to stretch the ship to fit the button exactly, but I've yet to find it. I also have to find a way to do this in Java (not CSS or FXML) because the Java code will have to move icons around.

这是我的代码:

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);
}

我一直在谷歌搜索几个小时,但我找不到一个似乎适用于此的拉伸图像到父解决方案。有什么我想念的吗?

I've been Googling for a few hours, but I can't find a "stretch image to parent" solution that seems to apply here. Is there something I am missing?

推荐答案

    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

这篇关于javafx拉伸图像填充按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆