我对如何将图形导出到svg或graphml有点困惑。截至目前,forum.jgraph.com上的api,示例或主题都没有帮助过我。
我需要将图形导出到svg和graphml。即使布局正确,我也有svg显示节点和边缘,但是我缺少节点名称和指定颜色等信息。
使用graphml我还不知道如何获得正确的xml代码甚至可以显示正常运行的图形。
是否有任何指南/工作流程可以帮助我在JGraphX中导出?
提前感谢您的帮助,
克里斯
答案 0 :(得分:3)
为了保存图形,您必须调用mxCellRendered将图形渲染到mxicanvas,从中获取Document(dom文档)。 从渲染器它是这样的: mxGraph.drawCell() - > mxGraph.drawState() - > mxICanvas.drawCell() - > mxICanvas.drawShape() mxICanvas只知道单元格的几何和样式。
我也想在svg文件中添加cell id属性,所以我做了以下
保存为svg图的功能如下:
// use the extended svg canvas, where the cell id is added as attribute
public void createSVG(mxGraphExtended g) {
String filename = "\home\koula\graph.svg";
mxSvgCanvasExtended canvas = (mxSvgCanvasExtended) mxCellRenderer.drawCells(
g, null, 1, null, new CanvasFactory() {
public mxICanvas createCanvas(int width, int height) {
mxSvgCanvasExtended canvas = new mxSvgCanvasExtended(mxDomUtils
.createSvgDocument(width, height));
canvas.setEmbedded(true);
return canvas;
}
});
try {
mxUtils.writeFile(mxXmlUtils.getXml(canvas.getDocument()), filename);
} catch (IOException e) {
e.printStackTrace();
}
}
重写drawCell():
public class mxGraphExtended extends mxGraph {
@Override
public void drawCell(mxICanvas canvas, Object cell) {
// add the cell's id as a style attribute
// cause canvas only get the style and geometry
mxCellState state = this.getView().getState(cell);
state.getStyle().put("cellid", ((mxCell)cell).getId());
super.drawCell(canvas, cell);
}
}
重写的drawShape()如下:
public class mxSvgCanvasExtended extends mxSvgCanvas {
//... have coppied only the related code
@Override
public Element drawShape(int x, int y, int w, int h,
Map<String, Object> style)
{
//...
// Draws the shape
String shape = mxUtils.getString(style, mxConstants.STYLE_SHAPE, "");
String cellid = mxUtils.getString(style, "cellid", "");
Element elem = null;
// ...
// e.g. if image, add the cell id
if (shape.equals(mxConstants.SHAPE_IMAGE)) {
String img = getImageForStyle(style);
if (img != null) {
// Vertical and horizontal image flipping
boolean flipH = mxUtils.isTrue(style,
mxConstants.STYLE_IMAGE_FLIPH, false);
boolean flipV = mxUtils.isTrue(style,
mxConstants.STYLE_IMAGE_FLIPV, false);
elem = createImageElement(x, y, w, h, img,
PRESERVE_IMAGE_ASPECT, flipH, flipV, isEmbedded());
/* so here we are */
// add the cell id atribute
if(!cellid.equals("")) {
elem.setAttribute("id", cellid);
}
}
} else if (shape.equals(mxConstants.SHAPE_LINE))
// ...
}// end drawShape
} // end class
希望这有帮助。