Wednesday, April 11, 2012

Creating a tree node diagram

I am trying to create a tree like node diagram, like the example image here. I have the following code:



    private void DrawNode(Graphics g, Node<T> node, float xOffset, float yOffset)
{
if (node == null)
{
return;
}

Bitmap bmp = (from b in _nodeBitmaps where b.Node.Value.Equals(node.Value) select b.Bitmap).FirstOrDefault();

if (bmp != null)
{
g.DrawImage(bmp, xOffset, yOffset);

DrawNode(g, node.LeftNode, xOffset - 30 , yOffset + 20);
DrawNode(g, node.RightNode, xOffset + 30, yOffset + 20);
}
}


My code is almost working. The problem I'm having is that some of the nodes are overlapping. In the picture above, nodes 25 and 66 are overlapping. The reason, I'm sure, is because its mathematically laying the left nodes and right nodes equal space, so the parent's right node overlaps with the adjacent parent's left node. How can I fix this problem?



UPDATE:



This is the code update I made after dtb's suggestion:



            int nodeWidth = 0;
int rightChildWidth = 0;

if (node.IsLeafNode)
{
nodeWidth = bmp.Width + 50;
}
else
{
int leftChildWidth = 0;

Bitmap bmpLeft = null;
Bitmap bmpRight = null;

if (node.LeftNode != null)
{
bmpLeft =
(from b in _nodeBitmaps where b.Node.Value.Equals(node.LeftNode.Value) select b.Bitmap).
FirstOrDefault();
if (bmpLeft != null)
leftChildWidth = bmpLeft.Width;
}
if (node.RightNode != null)
{
bmpRight =
(from b in _nodeBitmaps where b.Node.Value.Equals(node.RightNode.Value) select b.Bitmap).
FirstOrDefault();
if (bmpRight != null)
rightChildWidth = bmpRight.Width;
}

nodeWidth = leftChildWidth + 50 + rightChildWidth;
}


g.DrawImage(bmp, xOffset + (nodeWidth - bmp.Width) / 2, yOffset);

if (node.LeftNode != null)
{
DrawNode(g, node.LeftNode, xOffset, yOffset + 20);
}
if (node.RightNode != null)
{
DrawNode(g, node.RightNode, xOffset + nodeWidth - rightChildWidth, yOffset + 20);
}


Here is a screenshot from this code: Screen Shot





No comments:

Post a Comment