JavaFX: Max ImageView Size

This may sound like a duplicate of Set Max Size for JavaFX ImageView , but it is different.

I would like to limit the maximum size of the ImageView. Unfortunately, the only way to set the ImageView's size is with fitWidth and fitHeight, which however enlarges the image if it is smaller than the fit values.

I tried to set fitWidth / fitHeight to 0/0 and wrap the ImageView in a panel with maxWidth set - with no success (the image is displayed at its original size).

It seems to me that this is not possible for JavaFX, but I cannot believe it. But I couldn't find anything on the internet. Are there any tricks / bugs / workarounds?

+3


source to share


3 answers


If you don't want the image to stretch, you can use:

setPreserveRatio(true);

      



Then you can set width and height as you want
ImageView setPreserveRatio javadoc


The javadoc also has scaling rules in this method
+1


source


You just need to add an if statement to set the ones larger than maxsize to a fixed size. The rest will remain the same.



        ImageView im = new ImageView();
        im.setImage(image);
        im.maxHeight(690 - 10);   
        int yoursize = 690; 
        if(im.maxHeight(690 - 10)> yoursize ){
           im.setFitHeight(690- 10);  
           System.out.println("Fix Size : 690 ");
        }
        im.setPreserveRatio(true);
        im.setSmooth(true);
        im.setCache(true);           

      

0


source


You can get the actual resource of the image and ask for its width / height to use for the match values:

  Image image = imageView.getImage();

  double nativeWidth = image.getWidth();
  double nativeHeight = image.getHeight();

      

0


source







All Articles