1.思路分析:
1.首先肯定是读取数据库,将数据表中的这三列数据查出来并放进三个数组中;
2.新建一个Bitmap,所有要画的图形用Graphics来实现;
3.依据屏幕坐标,先画出X轴和Y轴,再标上刻度;
4.以X轴和Y轴为基础,算出每个数据在屏幕上的相对坐标,并画成折线;
5.在数据点上画点,并标出数据值;
6.修饰图形,并标注文字等信息,结束。
2.数据的获取
1.从数据库中获取数据
建立数据库连接并查询,可以专门新建一个C#类来提高代码复用率,也可以只写一个函数。下面的代码是原作者写的一个C#类SQL_Connection,放在App_Code文件夹下,专门用来执行数据库操作(我直接新建了一个数据库helper类,前面的文章里已经有了)代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
///
///公用的连接数据库的类
///
public class SQL_Connection
{
private string sql = null;
public SQL_Connection(string sql)
{
this.sql = sql;
}
public DataSet query()
{
string ConStr = "Data Source=……;Initial Catalog=……;Persist SecurityInfo=True;UserID=……;Password=……";
SqlConnection conn = new SqlConnection(ConStr);
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = this.sql;
cmd.CommandTimeout = 10000;
conn.Open();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adapter.Fill(ds);
conn.Close();
return ds;
}
}
2.在后台的CS文件中执行数据库查询,并将结果放在数组中,具体代码如下:
//查询数据库
string sql = "select * from manqi_cx where manqpfl <>0 and manqpfl1<>0 and manqpfl2<>0 and bmid=2";
SQL_Connection sqlCon = new SQL_Connection(sql);
DataSet ds = sqlCon.query();
//将结果放进数组中
double[] manqpfl = new double[TotalMonths];
double[] manqpfl1 = new double[TotalMonths];
double[] manqpfl2 = new double[TotalMonths];
for (int i = 0; i
{
manqpfl[i] = Convert.ToDouble(ds.Tables[0].Rows[i]["manqpfl"]);
manqpfl1[i] = Convert.ToDouble(ds.Tables[0].Rows[i]["manqpfl1"]);
manqpfl2[i] = Convert.ToDouble(ds.Tables[0].Rows[i]["manqpfl2"]);
}
3.具体实现
1.新建Bitmap,并用Graphics来画图和标注文字,具体代码如下:
Bitmap image = new Bitmap(width, height);
Graphics graphics = Graphics.FromImage(image);
try
{
graphics.Clear(Color.White);
Font font = new Font("Arial", 9, FontStyle.Regular);//坐标刻度所使用的字体
Font font1 = new Font("宋体", 15, FontStyle.Regular);//图片标题所使用的字体
Font font2 = new Font("