[英]JavaFX - Converting chart to image
我有一個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/
這將需要一個節點
我已將其與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();
}
});
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.