标签:
项目中有一项需求,需要将项目中的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(3, 3); this.panelcontent.Height = tree.getTotalLeafNum(node) * 20 + 50; this.panelcontent.Width = tree.getDeepthTree(node) * 50 + 100; 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 = 0; saveFileDialog.RestoreDirectory = true; saveFileDialog.CreatePrompt = true; saveFileDialog.Title = "导出文件到"; DateTime now = DateTime.Now; saveFileDialog.FileName = now.Year.ToString().PadLeft(2) + now.Month.ToString().PadLeft(2, ‘0‘) + now.Day.ToString().PadLeft(2, ‘0‘) + "-" + now.Hour.ToString().PadLeft(2, ‘0‘) + now.Minute.ToString().PadLeft(2, ‘0‘) + now.Second.ToString().PadLeft(2, ‘0‘) + "_datoutput.jpg"; saveFileDialog.Filter = "Jpg Files|*.jpg"; if (saveFileDialog.ShowDialog() == DialogResult.OK) { Rectangle rect = new Rectangle(0, 0, 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[0].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 = 0; TreeNode rt = treenode; if (rt.Nodes.Count > 0) { foreach (TreeNode tr in rt.Nodes) { int temp = 1 + getDeepthTree(tr); if (temp > deepth) { deepth = temp; } } } else { deepth = 1; } return deepth; }
/// <summary> /// 获取所有叶子节点个数 /// </summary> /// <param name="t"></param> /// <returns></returns> public static int getTotalLeafNum(TreeNode t) { int num = 0; if (t.Nodes.Count > 0) { foreach (TreeNode tr in t.Nodes) { num += getTotalLeafNum(tr); } } else { num = 1; } return num; }
标签:
原文地址:http://www.cnblogs.com/silent2012/p/4487509.html