效果如下图:

源代码:
<%@ 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页面接收后直接根据百分比画出矩形。
本代码分本人撰写,觉得好用遂共享出来!不足之处欢迎指导!
浙公网安备 33010602011771号