项目中有一项需求,需要将项目中的treeview控件展示的树状结构直接导成一张图片。网上方法很多,但很多都是屏幕截屏,我的解决思路是新建一个用户控件,将主窗体的Treeview的数据传给用户控件(不要直接用treeview做参数,可能会有问题),控件中将TreeView放到一个panel中,根据tree的节点深度和叶子节点个数来调整panel的高度和宽度,然后使用panel内置方法导出即可。具体步骤如下:
1. 新建用户控件 控件主要代码如下
public partial class uc_outputtree : UserControl
{
private TreeView treeoutput;
private Panel panelcontent; public uc_outputtree(TreeNode node)
{
InitializeComponent();
this.treeoutput = new TreeView();
treeoutput.Nodes.Clear();
treeoutput.Nodes.Add((TreeNode)node);
treeoutput.ExpandAll();
treeoutput.Dock = DockStyle.Fill; this.panelcontent = new Panel();
this.panelcontent.Location = new System.Drawing.Point(, );
this.panelcontent.Height = tree.getTotalLeafNum(node) * + ;
this.panelcontent.Width = tree.getDeepthTree(node) * + ;
this.panelcontent.Controls.Add(this.treeoutput);
} /// <summary>
/// 定义委托
/// </summary>
public delegate void UCeventOutPut();
/// <summary>
/// 事件
/// </summary>
public event UCeventOutPut UCOutPutEvent; public void TreeOutPut()
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.FilterIndex = ;
saveFileDialog.RestoreDirectory = true;
saveFileDialog.CreatePrompt = true;
saveFileDialog.Title = "导出文件到"; DateTime now = DateTime.Now;
saveFileDialog.FileName = now.Year.ToString().PadLeft() + now.Month.ToString().PadLeft(, '')
+ now.Day.ToString().PadLeft(, '') + "-" + now.Hour.ToString().PadLeft(, '')
+ now.Minute.ToString().PadLeft(, '') + now.Second.ToString().PadLeft(, '') + "_datoutput.jpg"; saveFileDialog.Filter = "Jpg Files|*.jpg";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
Rectangle rect = new Rectangle(, , this.treeoutput.ClientRectangle.Width, this.treeoutput.ClientRectangle.Height);
using (Bitmap bmp = new Bitmap(rect.Width, rect.Height, PixelFormat.Format16bppRgb555))
{
this.panelcontent.DrawToBitmap(bmp, rect);
bmp.Save(saveFileDialog.FileName, ImageFormat.Jpeg); UCOutPutEvent();
}
}
}
}
2. 主窗体引用控件
internal void DataOutPutPic()
{
uc_outputtree uc_outputtree = new uc_outputtree((TreeNode)this.Tree_Network.Nodes[].Clone());
uc_outputtree.UCOutPutEvent += new uc_outputtree.UCeventOutPut(ucExport_UCOutPutEvent);
uc_outputtree.TreeOutPut();
uc_outputtree.Dispose();
} void ucExport_UCOutPutEvent()
{
MessageBox.Show("导出完成");
}
3. tree的算法
/// <summary>
/// 获取节点深度
/// </summary>
/// <param name="treenode"></param>
/// <returns></returns>
public static int getDeepthTree(TreeNode treenode)
{
int deepth = ;
TreeNode rt = treenode; if (rt.Nodes.Count > )
{
foreach (TreeNode tr in rt.Nodes)
{
int temp = + getDeepthTree(tr);
if (temp > deepth)
{
deepth = temp;
}
}
}
else
{
deepth = ;
} return deepth;
}
/// <summary>
/// 获取所有叶子节点个数
/// </summary>
/// <param name="t"></param>
/// <returns></returns>
public static int getTotalLeafNum(TreeNode t)
{
int num = ;
if (t.Nodes.Count > )
{
foreach (TreeNode tr in t.Nodes)
{
num += getTotalLeafNum(tr);
}
}
else
{
num = ;
}
return num;
}