我有一个XYChart,它显示X轴上的一天中的小时数。 我想保存整个图表的图像(或pdf)。 但是当我显示图表时,我无法全部显示,它太大了,因此我只显示一小部分(约1/4)。
我找到了这段代码,可以让我对窗格中显示的内容进行快照:
@FXML
public void saveAsPng() {
WritableImage image = chart.snapshot(new SnapshotParameters(), null);
File file = new File(path);
try {
ImageIO.write(SwingFXUtils.fromFXImage(image, null), "png", file);
} catch (IOException e) {
e.printStackTrace();
}
}
但是,我找不到将整个图表保存为图像的方法,而不显示它?
有人找到了办法吗?
非常感谢您的帮助!
参考:http://code.makery.ch/blog/javafx-2-snapshot-as-png-image/
答案 0 :(得分:0)
这需要一个节点
我已将其与Charts一起使用,因此我们可以将图像嵌入报表中,但应与任何Node一起使用。
void doResize(final Node node, final File file, final int aWidth, final int aHeight) {
final AnchorPane anchorPane = new AnchorPane();
anchorPane.setMinSize(aWidth, aHeight);
anchorPane.setMaxSize(aWidth, aHeight);
anchorPane.setPrefSize(aWidth, aHeight);
final ScrollPane scrollPane = new ScrollPane();
scrollPane.setContent(anchorPane);
final JFXPanel fxPanel = new JFXPanel();
fxPanel.setScene(new Scene(scrollPane));
final JFrame frame = new JFrame();
final Pane previousParentPane = (Pane) node.getParent();
frame.setSize(new Dimension(64, 64));
frame.setVisible(false);
frame.add(fxPanel);
anchorPane.getChildren().clear();
AnchorPane.setLeftAnchor(node, 0.0);
AnchorPane.setRightAnchor(node, 0.0);
AnchorPane.setTopAnchor(node, 0.0);
AnchorPane.setBottomAnchor(node, 0.0);
anchorPane.getChildren().add(node);
anchorPane.layout();
try {
final SnapshotParameters snapshotParameters = new SnapshotParameters();
snapshotParameters.setViewport(new Rectangle2D(0.0, 0.0, aWidth, aHeight));
ImageIO.write(SwingFXUtils.fromFXImage(anchorPane.snapshot(snapshotParameters, new WritableImage(aWidth, aHeight)), new BufferedImage(aWidth, aHeight, BufferedImage.TYPE_INT_ARGB)), "png", file);
}
catch (final Exception e) {
e.printStackTrace();
}
finally {
Platform.runLater(new Runnable() {
@Override
public void run() {
// Return the node back into it's previous parent
previousParentPane.getChildren().clear();
AnchorPane.setLeftAnchor(node, 0.0);
AnchorPane.setRightAnchor(node, 0.0);
AnchorPane.setTopAnchor(node, 0.0);
AnchorPane.setBottomAnchor(node, 0.0);
previousParentPane.getChildren().add(node);
frame.dispose();
}
});
}
}