Drawing a graph, although it sounds intuitive, is a tricky task. It usually involves a number of sophisticated algorithms and even more numerous parameters to set up the layout.
QuickGraph comes with a Managed C++ wrapper of Graphviz, a famous graph drawing library from AT&T. In this blog, I will show how to draw a graph in a few lines.
Let's build a dependency graph between some good old C files:
// create a new adjacency graph AdjacencyGraph g = new AdjacencyGraph(false); // adding files and storing names IVertex boz_h = g.AddVertex(); IVertex zag_cpp = g.AddVertex(); IVertex yow_h = g.AddVertex(); ... // adding dependencies g.AddEdge(dax_h, foo_cpp); g.AddEdge(dax_h, bar_cpp); ...
At this point, the graph structure is built and ready to be drawed by graphviz. You need to create an instance of QuickGraph.Algorithms.Graphviz.GraphvizAlgorithm and call it's write method:
QuickGraph.Algorithms.Graphviz.GraphvizAlgorithm
// creating graphviz algorithm GraphvizAlgorithm gw = new GraphvizAlgorithm( g, // graph to draw ".", // output file path GraphvizImageType.Png // output file type ); // outputing to graph. gw.Write("filedependency");
And the result is:
That's not so bad but we would like to see the names of the files. First thing to do, is to tell QuickGraph to produce NamedVertex vertices instead of Vertex. This is done by feeding the AdjacencyGraph constructor with two class factories, one for the vertices, one for the edges:
AdjacencyGraph
AdjacencyGraph g = new AdjacencyGraph( new NamedVertexProvider(), new EdgeVertexProvider(), false);
The NamedVertex class a Name property that we can use to store the name of the file:
// adding files and storing names NamedVertex boz_h = (NamedVertex)g.AddVertex(); boz_h.Name = "boz.h"; NamedVertex zag_cpp = (NamedVertex)g.AddVertex(); zag_cpp.Name = "zag.cpp"; NamedVertex yow_h = (NamedVertex)g.AddVertex(); yow_h.Name = "yow.h";
The last step is add attach an event handler to the event of GraphvizAlgorithm that renders the vertices and add the name property:
GraphvizAlgorithm
// outputing graph to png GraphvizAlgorithm gw = new GraphvizAlgorithm( g, // graph to draw ".", // output file path GraphvizImageType.Png // output file type ); gw.FormatVertex +=new FormatVertexEventHandler(gw_FormatVertex); gw.Write("filedependency"); } private void gw_FormatVertex(object sender, FormatVertexEventArgs e) { NamedVertex v = (NamedVertex)e.Vertex; e.VertexFormatter.Label = v.Name; }
and now the result is much better:
Page rendered at Sunday, September 07, 2008 8:57:40 PM UTC
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.