首页 文章

JavaFX - 将图表转换为图像

提问于
浏览
0

我有一个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/

1 回答

  • 0

    这将占用一个节点

    • 将其父级更改为固定大小的锚点窗格

    • 将锚定窗格放在滚动窗格中

    • 在不可见的JFrame窗口中打开滚动窗格

    • 将节点另存为图像

    • 将节点返回给它的前一个父节点 .

    我已经将它用于图表,因此我们可以将图像嵌入到报告中,但是应该可以与任何节点一起使用 .

    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();
                }
            });
        }
    }
    

相关问题