调整ImageView的大小

时间:2018-06-21 17:42:45

标签: imageview resize javafx-8 cell gridpane

我有一个GridPane(4x5),所有的单元格都有一个AnchorPane,它包含一个ImageView。我需要调整图像的大小,以便在gridPane(因此它是单元格)更改大小后就完全覆盖单元格。

当单元格的大小增加时,我设法正确调整了图像的大小,但是当单元格变得更小时,图像没有重新调整大小。 这导致部分覆盖了约束细胞的图像。

任何人都可以解释我在做什么,还是给我指示以进行适当的调整大小?

这是我的代码:

ImageView image = new ImageView("/dice/" + draftList.get(i) + ".png");
AnchorPane pane = ((AnchorPane)(gridpane.getChildren().get(i)));
pane.getChildren().add(image);
fitToParent(image,pane);

//method in the same class
private void fitToParent(ImageView image, AnchorPane pane) {
    image.fitWidthProperty().bind(pane.widthProperty());
    image.fitHeightProperty().bind(pane.heightProperty());
}

1 个答案:

答案 0 :(得分:0)

您可以尝试将ImageView类的setPreserveRatio(boolean)函数使用为true。这样可以使纵横比保持恒定。 例如:

ImageView iv = new ImageView(/*file path*/);
iv.setPreserveRatio(true);

Src:https://docs.oracle.com/javase/8/javafx/api/javafx/scene/image/ImageView.html

除此之外,您还可以尝试将resizable属性限制为false或设置最小宽度和高度,以使图像不会被部分覆盖

Src:https://docs.oracle.com/javase/8/javafx/api/javafx/scene/layout/Region.html#resize-double-double-

相关问题