将带有自定义顶点组件的JGraphX图导出到图像

时间:2017-06-01 11:05:15

标签: swing jgraphx

我有一个图表会覆盖createComponents中的mxGraphComponent,以便将每个顶点渲染为JTable。虽然我预计mxCellRenderer.create*Document无法处理它,但我希望用

保存到图像
BufferedImage image = mxCellRenderer.createBufferedImage(graphComponent.getGraph(), null, 1.0, null, graphComponent.isAntiAlias(), null);
ImageIO.write(image, "PNG", new File("C:\\Temp\\graph.png"));

会(当然,现在我看着它,它显然不能:它只获得mxGraph作为输入,而不是mxGraphComponent!)。有没有办法将图形保存为包含自定义渲染器的图像?

1 个答案:

答案 0 :(得分:0)

这适用于我的用例

JViewport viewport = graphComponent.getViewport();
Color savedBackground = viewport.getBackground();
viewport.setBackground(new Color(0, 0, 0, 0));
try {
    Dimension size = viewport.getPreferredSize();
    BufferedImage image = new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g = image.createGraphics();
    viewport.printAll(g);
    g.dispose();
    try {
        ImageIO.write(image, "png", target.getFile());
    } catch (IOException e1) {
        NotificationsUtil.showError("Failed to save image", e1);
    }
} finally {
    viewport.setBackground(savedBackground);
}