JFX scale image up and down to parent

寵の児 提交于 2019-12-10 18:18:37

问题


I am attempting to have an ImageView that scales with its parent. I have searched through every StackOverflow post I can find on this, and here is what I've tried:

        taggedImage.setPreserveRatio(true);
    //taggedImage.fitWidthProperty().bind(
    //      Bindings.min(imagePane.widthProperty(), imagePane.widthProperty()));
    //taggedImage.fitHeightProperty().bind(
    //      Bindings.min(imagePane.heightProperty(), imagePane.heightProperty()));
    taggedImage.fitWidthProperty().bind(imagePane.widthProperty());
    taggedImage.fitHeightProperty().bind(imagePane.heightProperty());

The commented lines I tried as well and the issue with these approaches is that when the imageview binds to the parent, the parent can only scale up and not down. Therefore, if you increase the size of the window, the picture will get bigger. If you decrease the size of the picture again, it doesn't decrease the picture size. In this example, imagePane is a StackPane. I have also tried a borderFrame. As well, I've tried using a Pane as the parent. This way, the image successfully scales up and down. However, the image isnt centered and is always in the top left corner of the pane if it doesnt match the size of the pane exactly.

Scene Tree: https://gyazo.com/45e0daebbfd98dfd3446185d21eb91ee

Values:

Top gridpane:
https://gyazo.com/f48ebb39f48d876a02d44792a73eaad4
lower level gridpane:
https://gyazo.com/3399d9f3ab00e8babd36ee3b0e3b27ba
BorderPane:
https://gyazo.com/51c24f8de50ae3865a299fdddf3a1490
ImageView:
https://gyazo.com/7dfc1071d2b516a83baed301596be2b9

Note, here I'm trying it with a borderpane instead of what I was using before. However, the result is the same no matter which object is the parent of the imageview.


回答1:


Solved. I've been messing around and found a fix. This isn't exactly intuitive but it worked for me: I left the image inside the borderframe and, in the java code, I created a pane in the same part of the gridpane as the image. I then bound the imageview's width and height to the pane. Then, the centering of the image was correct as well as the scaling. Here is what i did:

    imageView.setPreserveRatio(true);
    Pane pane = new Pane();
    testGridPane.add(pane, 1, 1);
    imageView.fitWidthProperty().bind(pane.widthProperty());
    imageView.fitHeightProperty().bind(pane.heightProperty());


来源:https://stackoverflow.com/questions/50918108/jfx-scale-image-up-and-down-to-parent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!