在使用 css 设置图像的按钮中的“ImageView”中设置图像大小

Set size of image in `ImageView` in button where image is set using css

我使用 fitWidthpreserveRatio 来调整 FXML 中 ImageView 的大小,但是图像没有缩放到它而是显示它的完整大小(在我的例子中太大了).如何使用 FXML 或 css?

设置图像的大小

FXML

<Button
        fx:id="buttonUp"
        GridPane.columnIndex="0"
        GridPane.rowIndex="0"
        onAction="#buttonUp">
    <graphic>
        <ImageView fitWidth="10.0" pickOnBounds="true" preserveRatio="true">
        </ImageView>
    </graphic>
</Button>

CSS

#buttonUp {
    -fx-graphic: url('up.png');
}

#buttonUp:pressed {
    -fx-graphic: url("up_pressed.png");
}

我不想要 JavaFX 代码解决方案,因为我想在 fxml 中保留我的样式并且 css。

如果这在 FXML 或 css 中真的不可能,那么我会承认用 java 来做,在那种情况下请发表评论。

FXML 格式的图像

当我尝试时

<ImageView id="buttonDownImage" fitHeight="40.0" fitWidth="40.0" pickOnBounds="true" preserveRatio="true">
    <image>
        <Image url="resources/down.png" />
    </image>
</ImageView>

然后是 java.lang.IllegalArgumentException: Invalid URL: Invalid URL or resource not found,而我确定文件在那里(css 可以找到它)并且 IntellJ 自动完成甚至建议从 resources 开始url.

未测试,但请尝试在 ImageView 本身上使用 CSS:

<Button
        fx:id="buttonUp"
        GridPane.columnIndex="0"
        GridPane.rowIndex="0"
        onAction="#buttonUp">
    <graphic>
        <ImageView id="buttonUpGraphic" fitWidth="10.0" pickOnBounds="true" preserveRatio="true">
        </ImageView>
    </graphic>
</Button>

然后在 CSS:

#buttonUp #buttonUpGraphic {
    -fx-image: url('up.png');
}

#buttonUp:pressed #buttonUpGraphic {
    -fx-image: url('up_pressed.png');
}

如果图片太大,好吧,那就调整一下吧!糟糕的解决方案,但总比没有好。