Cambiar el tamaño de las imágenes para que se ajusten al nodo padre


¿Cómo consigo que una imagen en una ImageView cambie de tamaño automáticamente para que siempre se ajuste al nodo padre?

Aquí hay un pequeño ejemplo de código:

@Override
public void start(Stage stage) throws Exception {
    BorderPane pane = new BorderPane();
    ImageView img = new ImageView("http://...");

    //didn't work for me:
    //img.fitWidthProperty().bind(new SimpleDoubleProperty(stage.getWidth())); 

    pane.setCenter(img);

    Scene scene = new Scene(pane);
    stage.setScene(scene);
    stage.show();
}
Author: The Unfun Cat, 2012-09-28

5 answers

@Override
public void start(Stage stage) throws Exception {
    BorderPane pane = new BorderPane();
    ImageView img = new ImageView("http://...");

    img.fitWidthProperty().bind(stage.widthProperty()); 

    pane.setCenter(img);

    Scene scene = new Scene(pane);
    stage.setScene(scene);
    stage.show();
}
 50
Author: The Unfun Cat,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-09-28 07:39:29

Esta es una mejor solución que enlazar la propiedad width (mejor porque a menudo cuando se enlaza un hijo a su contenedor, puede que no sea posible hacer que el contenedor sea más pequeño. En otras ocasiones, el contenedor podría incluso comenzar a crecer automáticamente).

La solución a continuación se basa en sobreescribir una ImageView para que podamos permitir que se comporte como 'redimensionable' y luego proporcionar implementaciones para el ancho/altura mínimo ,preferido y máximo. También es importante implementar realmente el llamada a resize ().

class WrappedImageView extends ImageView
{
    WrappedImageView()
    {
        setPreserveRatio(false);
    }

    @Override
    public double minWidth(double height)
    {
        return 40;
    }

    @Override
    public double prefWidth(double height)
    {
        Image I=getImage();
        if (I==null) return minWidth(height);
        return I.getWidth();
    }

    @Override
    public double maxWidth(double height)
    {
        return 16384;
    }

    @Override
    public double minHeight(double width)
    {
        return 40;
    }

    @Override
    public double prefHeight(double width)
    {
        Image I=getImage();
        if (I==null) return minHeight(width);
        return I.getHeight();
    }

    @Override
    public double maxHeight(double width)
    {
        return 16384;
    }

    @Override
    public boolean isResizable()
    {
        return true;
    }

    @Override
    public void resize(double width, double height)
    {
        setFitWidth(width);
        setFitHeight(height);
    }
}
 8
Author: ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-21 13:34:56

Utilice ScrollPane o simplemente Pane para superar este problema: Ejemplo:

 img_view1.fitWidthProperty().bind(scrollpane_imageview1.widthProperty()); 
 img_view1.fitHeightProperty().bind(scrollpane_imageview1.heightProperty());
 4
Author: Akshay Goyal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-09-16 15:18:26

Si desea que ImageView quepa dentro de un marco de Windows, utilice esta línea de código: ImageView.fitWidthProperty().bind(escena.widthProperty ()).

Tenga en cuenta que estoy usando widthProperty de la escena no el escenario. Ejemplo:

import java.io.FileNotFoundException;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.image.ImageView;
import javafx.stage.Stage;

public class MapViewer extends Application {

    public static void main(String[] args) {
        Application.launch(args);
    }

    @Override
    public void start(Stage primaryStage) throws FileNotFoundException {
        String strTitle = "Titulo de la Ventana";
        int w_width = 800;
        int w_height = 412;
        primaryStage.setTitle(strTitle);
        primaryStage.setWidth(w_width);
        primaryStage.setHeight(w_height);

        Group root = new Group();
        Scene scene = new Scene(root);

        final ImageView imv = new ImageView("file:C:/Users/utp/Documents/1.2008.png");
        imv.fitWidthProperty().bind(scene.widthProperty());
        imv.setPreserveRatio(true);

        root.getChildren().add(imv);
        primaryStage.setScene(scene);
        primaryStage.show();

    }

}

La radio de aspecto de la etapa (primaryStage) debe ser similar a la de la imagen (1.2008.png)

 1
Author: dew,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-11-24 19:36:25

Este es un método de ancho calculado que elimina el ancho de la barra de desplazamiento.

Primero:
myImageView.setPreserveRatio(true);

Cambios en el ancho de la barra de desplazamiento del monitor:

scrollPane.widthProperty().addListener((observable, oldValue, newValue) -> {
            myImageView.setFitWidth(newValue.doubleValue() - (oldValue.doubleValue() - scrollPane.getViewportBounds().getWidth()));
        });

Ancho de la barra de desplazamiento:
oldValue.doubleValue() - scrollPane.getViewportBounds().getWidth()

¿Cómo configuro el ancho de inicio?
después de primaryStage.show();

myImageView.setFitWidth(scrollPane.getViewportBounds().getWidth());

 0
Author: sambuca,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-23 07:46:35