Centering an image in an ImageView
So, after days of calculation, I managed to find a good way to do it.
I post it here in case of someone would like to achieve it.
I created a method that only needs access to the imageView :
public void centerImage() {
Image img = imageView.getImage();
if (img != null) {
double w = 0;
double h = 0;
double ratioX = imageView.getFitWidth() / img.getWidth();
double ratioY = imageView.getFitHeight() / img.getHeight();
double reducCoeff = 0;
if(ratioX >= ratioY) {
reducCoeff = ratioY;
} else {
reducCoeff = ratioX;
}
w = img.getWidth() * reducCoeff;
h = img.getHeight() * reducCoeff;
imageView.setX((imageView.getFitWidth() - w) / 2);
imageView.setY((imageView.getFitHeight() - h) / 2);
}
}
Here is an example code that might be a solution for your case:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
public class Test extends Application {
@Override
public void start(Stage primaryStage) {
Image image = new Image("https://upload.wikimedia.org/wikipedia/commons/a/a7/Frankenstein's_monster_(Boris_Karloff).jpg");
ImageView imageView = new ImageView();
imageView.setImage(image);
imageView.setPreserveRatio(true);
imageView.setFitWidth(400);
imageView.setFitHeight(300);
BorderPane pane = new BorderPane();
pane.setPrefSize(400, 300);
pane.setCenter(imageView);
primaryStage.setScene(new Scene(pane));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
And the result: