C# 自己绘制报表,GDI你会用吗?
转自:爱符号 http://www.afuhao.com/article_articleId-175_articleGroupId-42.shtml
如果你打算在C#里面自己绘制报表时,肯定要画表格对吧,那么你会画吗?
下面给一个简单的例子,至于多个单元格合并,请自己去实现,也就是坐标计算的事情。
至于画图,用GDI,还是DirectX画,自己选择,不过这里主要讲的是算法:坐标计算以及画的过程。
注意不要每个列都画一个矩形,很浪费的,因为都重叠了。
下面是核心代码
1 using System; 2 using System.Drawing; 3 using System.Windows.Forms; 4 5 namespace GDITableDemo { 6 public partial class Form1 : Form { 7 public Form1() { 8 InitializeComponent(); 9 } 10 11 private void button1_Click(object sender, EventArgs e) { 12 string[] columns = textBox1.Text.Split(','); 13 14 Font font = panel1.Font;//字体 15 Brush color = Brushes.Black;//颜色 16 Brush border = new SolidBrush(panel1.ForeColor);//用前景色画边框 17 Pen borderStyle =new Pen(border, 1); 18 19 //从什么位置开始画 20 float top = 0F;//Y坐标 21 float left = 0F;//X坐标 22 //画笔X坐标偏移量,left1:最后一次位置,left2当前最远位置 23 float left1 = left, left2 = 0F; 24 float textLeft=0F;//文本X坐标 25 float textTop = 0F;//文本Y坐标 26 float textWidth=0F;//文本宽度 27 float textHeight=0F;//文本高度 28 const float columnHeight = 30F;//行高,包括边框在内 29 const float columnPadding = 10F;//每一列左右多出10像素 30 31 Graphics g = Graphics.FromHwnd(panel1.Handle); 32 textHeight = font.GetHeight(g);//高 33 textTop = (columnHeight - textHeight) / 2;//上边 34 for (int i = 0; i < columns.Length; i++) { 35 //先计算文本 36 textWidth= g.MeasureString(columns[i],font).Width;//宽 37 textLeft = left1 + columnPadding;//左边 38 left2=textLeft+textWidth+columnPadding; 39 40 //先画左边框 41 g.DrawLine(borderStyle, left1, top, left1, columnHeight); 42 43 //画文字 44 g.DrawString(columns[i], font, color, textLeft, textTop); 45 //注意左边的位置要开始偏移了 46 left1 = left2; 47 } 48 g.DrawLine(borderStyle, left, top, left2, top);//上边框 49 g.DrawLine(borderStyle, left, columnHeight, left2, columnHeight);//下边框 50 g.DrawLine(borderStyle, left2, top, left2, columnHeight);//右边框 51 52 } 53 } 54 }
下面贴图啦!

下面传另一个版本,变态一点的列绘制
看截图吧,代码就不贴了,太长了,图中是两个按钮都点过了。
转自:爱符号 http://www.afuhao.com/article_articleId-175_articleGroupId-42.shtml
浙公网安备 33010602011771号