运行效果如下图:
设计上面的柱状图和折线图其实并没有什么难度,主要是各个坐标的计算,完全是精细活。首先在窗体在添加了一个tabControl控件来切换柱状图和折线图的显示,在tabPage1中显示柱状图,在tabPage2中显示折线图。然后在各自的Page页属性中定义Paint事件,具体实现过程可以从下面的代码中看到。
代码如下:
添加头文件:
using System.Drawing.Drawing2D;
private void tabPage1_Paint(object sender, PaintEventArgs e)
{
BackColor = Color.White;
//标题
Graphics g = tabPage1.CreateGraphics();
Font f = new Font("宋体", 24, FontStyle.Regular);
Pen p = new Pen(Color.Blue);
g.DrawString("报名及考试统计柱状图", f, p.Brush, 200, 20);
//画表格
for (int i = 0; i <= 9; i++)
{
g.DrawLine(p, 30, 90 + 31 * i, 620, 90 + 31 * i);
}
for (int i = 1; i <= 14; i++)
{
g.DrawLine(p, 30 + 42 * i, 60, 30 + 42 * i, 370);
}
Pen MyPen = new Pen(Color.Blue, 2);
Point p1 = new Point(30, 60);
Point p2 = new Point(30, 370);
Point p3 = new Point(30, 370);
Point p4 = new Point(620, 370);
g.DrawLine(MyPen, p1, p2);
g.DrawLine(MyPen, p3, p4);
//红色图形部分
Pen drawPen = new Pen(Color.Red, 1);
SolidBrush mybrush = new SolidBrush(Color.Red);
e.Graphics.DrawRectangle(drawPen, 30 + 21, 370 - 41, 21, 41);
e.Graphics.FillRectangle(mybrush, 30 + 21, 370 - 41, 21, 41);
e.Graphics.DrawRectangle(drawPen, 30 + 42 * 2 + 21, 370 - 31 * 4 - 10, 21, 31 * 4 + 10);
e.Graphics.FillRectangle(mybrush, 30 + 42 * 2 + 21, 370 - 31 * 4 - 10, 21, 31 * 4 + 10);
e.Graphics.DrawRectangle(drawPen, 30 + 42 * 4 + 21, 370 - 31 * 2 - 20, 21, 31 * 2 + 20);
e.Graphics.FillRectangle(mybrush, 30 + 42 * 4 + 21, 370 - 31 * 2 - 20, 21, 31 * 2 + 20);
e.Graphics.DrawRectangle(drawPen, 30 + 42 * 6 + 21, 370 - 31 * 1 - 20, 21, 31 * 1 + 20);
e.Graphics.FillRectangle(mybrush, 30 + 42 * 6 + 21, 370 - 31 * 1 - 20, 21, 31 * 1 + 20);
e.Graphics.DrawRectangle(drawPen, 30 + 42 * 8