效果如:
原始碼:
<%@ WebHandler Language="C#" Class="ChartHandler" %>using System; using System.Web; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging;public class ChartHandler : IHttpHandler { public void ProcessRequest (HttpContext context) { string strpercent = context.Request.QueryString["percent"].TrimEnd('%'); decimal percent = Convert.ToDecimal(strpercent); using (Bitmap bitmap = new Bitmap(100, 16)) { if (percent == -1) { Bitmap bitmap1 = new Bitmap(1, 1); Graphics graphics1 = Graphics.FromImage(bitmap1); graphics1.SmoothingMode = SmoothingMode.AntiAlias; graphics1.Clear(Color.White); context.Response.ContentType = "text/gif"; context.Response.Clear(); context.Response.BufferOutput = true; bitmap1.Save(context.Response.OutputStream, ImageFormat.Gif); return; } using (Graphics graphics = Graphics.FromImage(bitmap)) { graphics.SmoothingMode = SmoothingMode.AntiAlias; graphics.Clear(Color.White); Rectangle rect = new Rectangle(0, 0, 100, 16); graphics.DrawRectangle(Pens.Black, rect); int width = Convert.ToInt32(percent); Rectangle fillRect = new Rectangle(0, 0, width, 16); //根據百分比 畫矩形 if (width == 100) { graphics.FillRectangle(Brushes.Green, fillRect);//如果百分比為一百,進度條用綠色顯示,表示已完成 } else if(width==0) { graphics.Clear(Color.Gray); graphics.FillRectangle(Brushes.Gray, fillRect);//百分比為0,進度條用灰色顯示,表示未開始 } else { graphics.FillRectangle(Brushes.Blue, fillRect);//進行中的,用藍色顯示 } context.Response.ContentType = "text/gif"; context.Response.Clear(); context.Response.BufferOutput = true; bitmap.Save(context.Response.OutputStream, ImageFormat.Gif); } } }//下面是必須要的 public bool IsReusable { get { return false; } }}
頁面調用方式:
<ItemTemplate> <img alt=' <%# fun(Convert.ToInt16(Eval("State")))%>' src='<%# Eval("State").ToString()==""?"Chart.ashx?percent=-1":"Chart.ashx?percent="+fun(Convert.ToInt16(Eval("State"))) %>' visible='<%# Eval("State").ToString()!="" %>' /> </ItemTemplate>
使用說明:在前台頁面中傳入一個類似25.30%這樣帶百分比符號的數字,ashx頁面接收後直接根據百分比畫出矩形。
本代碼分本人撰寫,覺得好用遂共用出來!不足之處歡迎指導!