获取 javaFX 8 中节点的屏幕坐标
Get screen coordinates of a node in javaFX 8
我正在 Windows 8.1 64 位上开发 JavaFX 应用程序,内存为 4GB,JDK 版本 8u45 64 位。
我想使用 Robot
捕获部分屏幕,但问题是我无法获取要捕获的锚点窗格的屏幕坐标,我不想使用 snapshot
因为输出质量不好。这是我的代码。
我已经看到这个link中的问题了
Getting the global coordinate 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();
}
}
我正在 Windows 8.1 64 位上开发 JavaFX 应用程序,内存为 4GB,JDK 版本 8u45 64 位。
我想使用 Robot
捕获部分屏幕,但问题是我无法获取要捕获的锚点窗格的屏幕坐标,我不想使用 snapshot
因为输出质量不好。这是我的代码。
我已经看到这个link中的问题了
Getting the global coordinate 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();
}
}