近几日,闲来无时感觉迅雷的下载进度显示模块做的不错,心血来潮,就简单写了一个控件。
我先直接上源码:
程序有注释的,第一次写,水平不高请各们高手指教。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
namespace Liyou.Progess
{
public partial class RectangleProgess : UserControl
{
/// <summary>
/// 网格列数
/// </summary>
private int cols = 50;
/// <summary>
/// 网格行数
/// </summary>
private int rows = 100;
/// <summary>
/// 存储变量的数组,其中X表示第几列,Y表示值
/// </summary>
private Point[] _Point;
/// <summary>
/// 控件的背景色
/// </summary>
private Color drawcolor = Color.Green;
/// <summary>
/// 控件当前值
/// </summary>
private int _value=0;
/// <summary>
/// 值
/// </summary>
public int DisplayValue
{
get
{
return _value;
}
set
{
_value = value;
}
}
/// <summary>
/// 绘制色
/// </summary>
public Color DrawColor
{
get
{
return drawcolor;
}
set
{
drawcolor = value;
}
}
/// <summary>
/// 是否开始显示进度
/// </summary>
public bool EnableDisplay
{
get
{
return timer1.Enabled;
}
set
{
timer1.Enabled = value;
}
}
/// <summary>
/// 返回和设计行值
/// </summary>
public int Rows
{
get
{
return rows;
}
set
{
if(value>=0&&value<=100)
rows = value;
}
}
/// <summary>
/// 高
/// </summary>
public int H
{
get
{
return this.Height;
}
set
{
this.Height = value;
}
}
/// <summary>
/// 宽
/// </summary>
public int W
{
get
{
return this.Width;
}
set
{
this.Width = value;
}
}
/// <summary>
///初始化
/// </summary>
public RectangleProgess()
{
InitializeComponent();
//初始化变量
_Point = new Point[cols];
InitPoint();
}
private void InitPoint()
{
//初始化变量,每个赋0值
for (int i = 0; i < _Point.Length; i++)
{
_Point[i] = new Point(i, 0);
}
}
/// <summary>
/// 关键代码,移位
///根据新传入的变量值依次向左移一位,最左一位的数据丢弃
/// </summary>
/// <param name="value"></param>
private void MoveBit(int value)
{
for (int i = _Point.Length - 1; i > 0; i--)
{
_Point[i] = new Point(i,_Point[i - 1].Y);
}
_Point[0] = new Point(0, value);
}
/// <summary>
/// 画图,进行显示
/// </summary>
private void Display()
{
Graphics g = this.CreateGraphics();
g.Clear(this.BackColor);
g.Dispose();
for (int i = 0; i < _Point.Length; i++)
{
DrawFromPoint(_Point[i]);
}
}
/// <summary>
/// 根据变量数组进行画图
/// </summary>
/// <param name="pi"></param>
private void DrawFromPoint(Point pi)
{
Graphics g = this.CreateGraphics();
SolidBrush brush = new SolidBrush(DrawColor);
Point pp=GetDrawPoint(pi);
g.FillRectangle(brush, pp.X, pp.Y, W / cols, pi.Y * H / rows);
g.Dispose();
}
/// <summary>
/// 计算相应点在画图中的坐标
/// </summary>
/// <param name="pi"></param>
/// <returns></returns>
private Point GetDrawPoint(Point pi)
{
int x = W - (pi.X + 1) * W / cols;
int y = H - (pi.Y * H / Rows);
return new Point(x, y);
}
private void timer1_Tick(object sender, EventArgs e)
{
MoveBit(DisplayValue);
Display();
}
}
}