我有一个组,其中包含一个矩形和顶部的图像。我希望矩形可以调整大小,并且图像应该具有固定大小,除非矩形小于图像的情况。然后图像应该随着矩形缩小。
图像还应该始终居中并有一些填充。
除了图像的缩小尺寸部分之外,我已经完成了大部分部分。我不知道为什么,但图像根本不会缩小。这就是我所拥有的。
Group group = new Group()
GeometryNode<Rectangle> rectangle = new GeometryNode<>();
rectangle.setGeometry(new Rectangle(0, 0, 60, 60));
ImageView imageView = new ImageView(image);
imageView.setPreserveRatio(true);
ImageViewPane imagePane = new ImageViewPane(imageView);
imagePane.setMinSize(0, 0);
imagePane.setMaxSize(50, 50);
StackPane stackPane = new StackPane();
stackPane.getChildren().add(rectangle);
stackPane.getChildren().add(imagePane);
group.getChildren().add(stackPane);
最佳答案
如果 StackPane
的尺寸发生变化,您希望 ImageView
的 fitWidth
和 fitHeight
属性也发生变化。所以你可以这样做
double padding = ... ;
imageView.setPreserveRatio(true);
imageView.fitWidthProperty().bind(
Bindings.min(stackPane.widthProperty().subtract(padding), image.widthProperty()));
imageView.fitHeightProperty().bind(
Bindings.min(stackPane.heightProperty().subtract(padding), image.heightProperty()));
关于JavaFX 缩小 ImageView 尺寸,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46278492/