图形的绘制涉及到的类并不是很多,如果要绘制图形,特别是这种数据源动态变化的图形,坐标位置的控制非常关键。
这个Demo采用oracle数据库为数据源:
CREATE TABLE IVAN_TEST
(
MAJOR VARCHAR2(50),
GRADE NUMBER,
ID NUMBER(10)
)
Html中加入:
<asp:Button ID="btnColumn" runat="server" Text="DrawColumn" OnClick="btnColumn_Click" /><br />
<asp:Image ID="imgColumn" runat="server" />
CS:()
protected void btnColumn_Click(object sender, EventArgs e)
...{
Bitmap img = new Bitmap(300,300);
Graphics g = Graphics.FromImage(img);
StringFormat drawFormat = new System.Drawing.StringFormat(StringFormatFlags.DirectionVertical);
StringFormat drawFormat1 = new System.Drawing.StringFormat(StringFormatFlags.DisplayFormatControl);
g.Clear(ColorTranslator.FromHtml("#F0F0F0"));
g.DrawString("Student Grade Column Chart", new Font("Arial",1, FontStyle.Bold),Brushes.Black , 100, 0,drawFormat1);
//get datasource
string sql = "select * from ivan_test";
DAL.ISDApp01 cDal = new DAL.ISDApp01();
DataSet ds = cDal.ExecuteQuery(sql);
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
...{
int grade = Convert.ToInt32(ds.Tables[0].Rows[i][1]); //grade
string Major = ds.Tables[0].Rows[i][0].ToString();
//注意坐标的控制
g.FillRectangle(new SolidBrush(GetColor(i)), (i * 35) + 15, 150 - grade, 20,
grade+50 );
g.DrawRectangle(new Pen(Color.Black), (i * 35) + 15, 150 - grade, 20,
grade + 50);
g.DrawString(Major, new Font("Arial", 12, FontStyle.Bold), Brushes.Red, (i * 35) + 20, 200,drawFormat);
g.DrawString(grade.ToString(), new Font("Arial", 12, FontStyle.Bold), Brushes.Red, (i * 35) + 20, 130 - grade );
}
//show chart
string Filepath = Server.MapPath("Images") + "//" + "Column.jpg?http://www.xvna.com";
if (File.Exists(Filepath))
...{
File.Delete(Filepath);
}
img.Save(Filepath, ImageFormat.Jpeg);
img.Dispose();
g.Dispose();
this.imgColumn.ImageUrl = Filepath;
}