我有一段代码,旨在在JavaFX中截取节点的屏幕截图:
public BufferedImage getSnapshot(final Node... hideNodes) {
Window window = getScene().getWindow();
Bounds b = localToScene(getBoundsInLocal());
int x = (int) Math.round(window.getX() + getScene().getX() + b.getMinX());
int y = (int) Math.round(window.getY() + getScene().getY() + b.getMinY());
int w = (int) Math.round(b.getWidth());
int h = (int) Math.round(b.getHeight());
try {
Robot robot = new Robot();
for(Node node : hideNodes) {
node.setOpacity(0);
node.getParent().requestLayout();
}
BufferedImage image = robot.createScreenCapture(new java.awt.Rectangle(x, y, w, h));
for(Node node : hideNodes) {
node.setOpacity(1);
node.getParent().requestLayout();
}
return image;
}
catch(AWTException ex) {
return null;
}
}
这段代码有个特点,就是在截图之前需要隐藏给定的节点(以防它们与节点重叠,某些情况下这是肯定会发生的)。
然而,我现在遇到了一个问题,就是找不到一种方法来强制重新绘制,以便在截图之前包括透明度更改 - 我唯一找到的参考是使用requestLayout()
,但并没有起作用。
应该调用哪些方法来强制重新绘制并等待重绘完成呢?
Image
转换为BufferedImage
,建议使用SwingFXUtils.fromFXImage。 - jewelsea