以下範例將教你怎麼在asp.net裡畫一個圓餅圖(Pie chart)並標上文字
步驟如下:
- 新增default.aspx,加入一個按鈕和image
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
<br />
<asp:Image ID="Image1" runat="server" />
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
- 並加入按鈕事件, 將pie chart產生
protected void Button1_Click(object sender, EventArgs e)
{
Image1.ImageUrl = "Image.aspx";
}
- 另外再新增Image.aspx,並在Image.aspx.cs加入繪圖程式
protected void Page_Load(object sender, EventArgs e)
{
// 設定回傳的 Type為Jpeg
Response.ContentType = "image/jpeg";
const int width = 200, height = 100;
Bitmap objBitmap = new Bitmap(width, height);
Graphics objGraphics = Graphics.FromImage(objBitmap);
// 設定白色背景
objGraphics.Clear(Color.White);
// Create solid brush.建立固定刷子, 顏色:紅色
SolidBrush redBrush = new SolidBrush(Color.Red);
// Create rectangle for ellipse.建立圓的方形範圍,
//1,2位數字表左上角的座標(x,y) :(0,0)
//3,4位數字表右上角的座標(x,y) :(200,100)
Rectangle rect = new Rectangle(0, 0, width, height);
//建立開始角度(以度為單位,依順時針方向測量之從 X 軸到派形區段的第一個邊的角度)
float startAngle = 0.0F;
//建立開扇角度(以度為單位,依順時針方向從 startAngle 參數到派形區段的第二個邊的角度)
float sweepAngle = 360.0F;
objGraphics.FillPie(redBrush, rect, startAngle, sweepAngle);
//寫字
Font myFont = new System.Drawing.Font("Helvetica", 10, FontStyle.Italic);
Brush myBrush = new SolidBrush(System.Drawing.Color.Red);
SolidBrush textBrush = new SolidBrush(Color.Black);
objGraphics.DrawString("50%", myFont, textBrush, 10, 10);
objBitmap.Save(Response.OutputStream, ImageFormat.Jpeg);
// clean up...
objGraphics.Dispose();
objBitmap.Dispose();
}
適用:
ASP.net 2.0以上
參考:
3. Charts for Windows Application using C#
4. Drawing in ASP.NET 2.0 and C#
沒有留言:
張貼留言