C#如何用Graphics画出一幅图表

C#如何用Graphics画出一幅图表

/// <summary>
/// 绘制折线图
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>

private void Form2_Paint(object sender, PaintEventArgs e)
{
//首先确定原点
Point centerPoint=new Point(180,340);
//自定义一个带有箭头的画笔
Pen pen = new Pen(Color.Black,1);
pen.EndCap = System.Drawing.Drawing2D.LineCap.ArrowAnchor;
//得到当前窗体的Graphics对象
Graphics g = e.Graphics;
//X轴和Y
//g.DrawLine(pens.Black,centerPoint,new Point(centerPoint.X+600,centerPoint.Y));
//g.DrawLine(Pens.Black, centerPoint, new Point(centerPoint.X, 40));
g.DrawLine(pen, centerPoint, new Point(centerPoint.X + 650, centerPoint.Y));
g.DrawLine(pen, centerPoint, new Point(centerPoint.X, 20));
//绘制X轴的点
for (int i = 0; i < 12; i++)
{
g.DrawLine(Pens.Black, new Point(centerPoint.X + (i + 1) * 50, centerPoint.Y), new Point(centerPoint.X + (i + 1) * 50, centerPoint.Y-5));
g.DrawString((i + 1).ToString() + "", this.Font, Brushes.Black, new PointF((centerPoint.X + (i + 1) * 50) - 7, centerPoint.Y + 3));
}
g.DrawString("X:月份",this.Font,Brushes.Black,new Point(828,355));
//绘制Y轴的点
for (int i = 0; i < 12; i++)
{
g.DrawLine(Pens.Black, new Point(centerPoint.X, centerPoint.Y - (i + 1) * 25), new Point(centerPoint.X + 5, centerPoint.Y-(i + 1) * 25));
//g.DrawLine(Pens.Black, new Point(centerPoint.X , centerPoint.Y), new Point(centerPoint.X + (i + 1) * 50, centerPoint.Y - 5));
g.DrawString(string.Format("{0}",(i+1)*10), this.Font, Brushes.Black, new PointF((centerPoint.X + 5) - 35, (centerPoint.Y - (i + 1) * 25)-5));
}

//计算十二个月销售额对应的坐标点
double[] data = { 56.2, 66.3, 98.4, 34.5, 55.6, 87.3, 81.4, 33.3, 46.4, 34.6, 114.5, 80.4};
PointF[] dataPoint = new PointF[data.Length];
for (int i = 0; i < data.Length ; i++)
{
float y = (float)(340 - data[i] * 2.5);
float x = centerPoint.X + (i + 1) * 50;
PointF point = new PointF(x, y);
dataPoint[i] = point;
}
//绘制十二个点的折线
for (int i = 0; i < data.Length ; i++)
{
g.DrawRectangle(Pens.Black, dataPoint[i].X, dataPoint[i].Y, 2, 2);
}

//将十二个点串成线
g.DrawLines(Pens.Black, dataPoint);

//方法二:Path方法
//GraphicsPath path = new GraphicsPath();//要导入using System.Drawing.Drawing2D;
//for (int i = 0; i < data.Length; i++)
//{
// path.AddRectangle(new RectangleF(dataPoint[i], new SizeF(2, 2)));
//}
//path.AddLines(dataPoint);
//g.DrawPath(Pens.Black, path);


g.DrawString("Y", this.Font, Brushes.Black, new Point(155,7));
g.DrawString("销售额:单位(万元)", this.Font, Brushes.Black, new Point(14, 14));
g.DrawString("某工厂某产品年度销售额图表",this.Font, Brushes.Black, new Point(420,14));
pen.Dispose();
}

上一篇:RabbitMQ消息队列(二):”Hello, World“


下一篇:Linux下使用fdisk扩展分区容量