Oren Levi
Oren Levi

Reputation: 73

JavaFX how to get the center of the X and Y axis - point [0,0] to be in the center of the image

enter image description hereMy JavaFX application can load an image and allow the user to click on it and get the X and Y coordinates printed out.

The problem is that the upper left corner of the image is the "center" [0,0] of the image instead of the actual image, any idea how to set the X and Y to be the center ?

Here is the code for loading the image:

BufferedImage bufferedImage = ImageIO.read(file);
Image image = SwingFXUtils.toFXImage(bufferedImage, null);
myImageView.setImage(image);
myImageView.setFitWidth(300);
myImageView.setPreserveRatio(true);
myImageView.setCache(true);

Here is the code for printing the location of the mouseClickedEvent:

myImageView.setOnMouseClicked(ev -> {
    System.out.println("[" + ev.getX() + ", " + ev.getY() + "]");
});

Red rectablge is the actual [0,0] Blue rectabgle is the expected [0,0]

Upvotes: 0

Views: 1466

Answers (1)

Oren Levi
Oren Levi

Reputation: 73

Found the answer: By calculating the offset between the actual center and the expected center, i was able to get the actual X and Y coordinates:

            double x = event.getX() - imageWidth / 2;
            double y = (event.getY() * -1) + (imageLength / 2);
            String msg ="[" + decimalFormat.format(x) + "," + decimalFormat.format(y) +"]";

Upvotes: 1

Related Questions