如何在JavaFX的ImageView中获取显示图像的宽度/高度?

7

我需要获取imageView中显示的图像的宽度/高度并将其与原始图像大小进行比较,而原始图像大小位于imageView.getImage().getWidth() / getHeight()中,并监听用户在应用程序GUI中调整图像大小的更改。

我从imageView.fitWidthProperty()中获取此大小,高度也类似,但我得到的是imageView的大小,而不是其中的图像:enter image description here

我获得了imageView(蓝色)的大小,但我需要显示图像(绿色)的大小。如何将其作为属性获取以便在用户调整窗口应用程序大小时进行监听(绿色也会改变大小,但它似乎有最大和最小大小,因此当达到最大或最小时,它会停止随imageView一起调整大小)。

我使用此属性在蓝色矩形下方右下角计算原始图像大小的百分比。

这可行吗?

E:下面是此选项卡的fxml:

<BorderPane fx:id="root" fx:controller="..."
        xmlns:fx="..." xmlns="..." stylesheets="@...css">
<center>
    <StackPane>
        <ImageView fx:id="..."/>
        <fx:include source="...fxml" fx:id="..."/>
    </StackPane>
</center>
<bottom>
    <VBox fx:id="..." minHeight="110" styleClass="small-padding" spacing="5">
        <HBox alignment="CENTER_RIGHT" spacing="5">
            <fx:include source="...fxml" resources="..."
                        fx:id="..."/>
        </HBox>
        <TextArea fx:id="..." promptText="%..." styleClass="-fx-description-text-area"/>
    </VBox>
</bottom>

3个回答

5

ImageView设置为保持纵横比时,必须手动计算实际尺寸。至少我没有找到其他方法。

double aspectRatio = image.getWidth() / image.getHeight();
double realWidth = Math.min(imageView.getFitWidth(), imageView.getFitHeight() * aspectRatio);
double realHeight = Math.min(imageView.getFitHeight(), imageView.getFitWidth() / aspectRatio);

简单解释一下:getFitHeight/Width 是你的蓝色矩形。在保持源图像的纵横比时,蓝色矩形的至少一侧必须与绿色矩形对应侧的长度相同。此外,绿色矩形始终位于蓝色矩形内部,因此调用了 Math.min()


3

~>1)

如果想要让Image覆盖整个ImageView,需要设置setPreserveRatio(false);并结合setSmooth(true);

~>2)

绿色边框的大小是原始图片的大小。

~>3)

在将Image添加到ImageView之前,您可以进行以下操作:

Image image = new Image("FILE:...");
image.getWidth( );
image.getHeight( );

这是图像的原始大小。

至于当图像在ImageView内显示时的大小:

imageView.getFitWidth();
imageView.getFitHeight();

对于场景内 ImageView 的大小(您问题中的蓝色边框):

imageView.getWidth();
imageView.getHeight();

ImageView类具有上述属性。


6
imageView.getFitWidth()无效。但我在imageView.boundsInParentProperty()中找到了需要的内容,问题解决了。 - xav9211
4
一样,你需要使用:listView.boundsInParentProperty().get().getWidth() - user1300214

0

我不知道有什么属性可以直接获取你想要的数字,但你可以提出这个改进建议给 JavaFX 的未来版本。

现在你可以编写一些代码来跟踪 ImageView 的所有属性,这些属性会影响显示图像的大小,然后自己计算显示的大小。对我来说,这听起来并不太复杂。


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