gpt4 book ai didi

java - 获取 javaFX 8 中节点的屏幕坐标

转载 作者:搜寻专家 更新时间:2023-10-31 08:14:46 24 4
gpt4 key购买 nike

我正在 Windows 8.1 64 位上开发 JavaFX 应用程序,内存为 4GB,JDK 版本为 8u45 64 位。

我想使用 Robot 捕获部分屏幕,但问题是我无法获取要捕获的 anchor Pane 的屏幕坐标,我不想使用snapshot 因为输出质量不好。这是我的代码。

我已经看到这个链接中的问题 Getting the global coordinate of a Node in JavaFX还有这个 get real position of a node in javaFX我尝试了所有答案,但没有任何效果,图像显示了屏幕的不同部分。

private void capturePane() {
try {
Bounds bounds = pane.getLayoutBounds();
Point2D coordinates = pane.localToScene(bounds.getMinX(), bounds.getMinY());
int X = (int) coordinates.getX();
int Y = (int) coordinates.getY();
int width = (int) pane.getWidth();
int height = (int) pane.getHeight();
Rectangle screenRect = new Rectangle(X, Y, width, height);
BufferedImage capture = new Robot().createScreenCapture(screenRect);
ImageIO.write(capture, "png", new File("image.png"));
} catch (IOException | AWTException ex) {
ex.printStackTrace();
}
}

最佳答案

由于您是从本地(而非布局)坐标开始的,因此请使用 getBoundsInLocal() 而不是 getLayoutBounds()。由于您想要转换为屏幕(而非场景)坐标,请使用 localToScreen(...) 而不是 localToScene(...):

private void capturePane() {
try {
Bounds bounds = pane.getBoundsInLocal();
Bounds screenBounds = pane.localToScreen(bounds);
int x = (int) screenBounds.getMinX();
int y = (int) screenBounds.getMinY();
int width = (int) screenBounds.getWidth();
int height = (int) screenBounds.getHeight();
Rectangle screenRect = new Rectangle(x, y, width, height);
BufferedImage capture = new Robot().createScreenCapture(screenRect);
ImageIO.write(capture, "png", new File("image.png"));
} catch (IOException | AWTException ex) {
ex.printStackTrace();
}
}

关于java - 获取 javaFX 8 中节点的屏幕坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31807329/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com