JavaFX如何将ImageView调整大小以适应AnchorPane。

3

我在AnchorPane中有一个ImageView,希望当AnchorPane大小改变时,以相同的比例调整图片大小。

请问有人能够解释一下如何实现吗?

非常感谢。

3个回答

3

您可以将图像视图的fitWidthfitHeight属性绑定到锚点面板的宽度和高度上:

imageView.fitWidthProperty().bind(anchorPane.widthProperty());
imageView.fitHeightProperty().bind(anchorPane.heightProperty());

如果您希望保持显示的图像比例,可以执行以下操作:
imageView.setPreserveRatio(true);

1
根据场景,您可能还需要将imageViewmanaged属性设置为false,以防止其影响AnchorPaneminpref大小。 - fabian
谢谢,但这并不是我想要的效果。我想保持AnchorPane边缘的距离。因此,如果Pane底部有30像素的距离,并且我调整了Pane的大小,我希望按钮能够按比例缩放以保持30像素的距离。这可能吗? - Bashfire
@Bashfire,什么按钮?你之前没有提到过按钮。你可能需要发布一个[MCVE]来演示你想要做什么。 - James_D
抱歉我使用ImageView作为按钮,但这并不重要,所以它只是一个普通的ImageView。 - Bashfire
2
只需执行 imageView.fitHeightProperty().bind(anchorPane.heightProperty().subtract(30))?(将 30 替换为您需要的任何值)。或者只需在另一个面板中包装图像视图 - 比如一个 StackPane,并将 StackPane 放置在 AnchorPane 中(然后绑定到堆栈面板的宽度和高度)。 - James_D

0

看一下答案。基本上你可以在你的项目中使用ImageViewPane


0

对我有效的唯一方法。 在视图上,监听 AnchorPane 的更改并设置 ImageView 大小。

init {
   myAnchorPane.widthProperty().addListener { observable, oldValue, newValue ->
            myImageView.fitWidth = myAnchorPane.width
            myImageView.fitHeight = 0.0
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接