C#WinForm工具箱自带的ProgressBar进度条控件的颜色默认为绿色,没有属性用来修改,很不方便。所以我们就需要重绘ProgressBar控件来达到我们想要的效果。 完成效果: 实现了进度条的颜色渐变以及value值的显示。
具体实现:本文采用的是拓展控件,即继承于ProgressBar,只需要在现有的基础上重绘一下就行。主要代码:重写OnPaint方法
protected override void OnPaint(PaintEventArgs e){Brush brush = null;Rectangle rect = new Rectangle(0, 0, base.Width, base.Height);// 边界线宽度为 2 rect.Height -= 4;rect.Width = ((int)(rect.Width * (((double)base.Value) / ((double)base.Maximum)))) - 4;brush = new LinearGradientBrush(this.ClientRectangle, _yStartColor, _yEndColor, LinearGradientMode.Horizontal);e.Graphics.FillRectangle(brush, 2, 2, rect.Width, rect.Height);// 写value值if (_yIsShowValue){SizeF sizeF = e.Graphics.MeasureString(base.Value.ToString(), _yValueFont);float x, y;x = base.Width / 2 - sizeF.Width / 2;y = base.Height / 2 - sizeF.Height / 2;e.Graphics.DrawString(base.Value.ToString(), _yValueFont, new SolidBrush(_yValueFontColor), x, y);}// 画边框e.Graphics.DrawRectangle(new Pen(Color.Silver), 0, 0, base.Width - 1, base.Height - 1);}
主要变量定义
public yProgressBarGradual(){InitializeComponent();base.SetStyle(ControlStyles.UserPaint, true);this.SetStyle(ControlStyles.DoubleBuffer, true); //双缓冲}private Color _yStartColor = Color.Transparent;private Color _yEndColor = Color.Green;private bool _yIsShowValue = false;private Font _yValueFont = new Font("宋体", 9, System.Drawing.FontStyle.Regular);private Color _yValueFontColor = Color.Black;
最后再添加相应的属性就好了
/// <summary>/// 渐变颜色起始颜色/// </summary>[Description("渐变颜色起始颜色"), Browsable(true), Category("1、自定义属性")]public Color ColorStart{get {return _yStartColor; }set{_yStartColor = value;Refresh();}}/// <summary>/// 渐变颜色结束颜色/// </summary>[Description("渐变颜色结束颜色"), Browsable(true), Category("1、自定义属性")]public Color ColorEnd{get {return _yEndColor; }set{_yEndColor = value;Refresh();}}/// <summary>/// 是否显示value值/// </summary>[Description("是否显示value值"), Browsable(true), Category("1、自定义属性")]public bool ShowValue{get {return _yIsShowValue; }set{_yIsShowValue = value;Refresh();}}/// <summary>/// 显示value值字体颜色/// </summary>[Description("显示value值字体颜色"), Browsable(true), Category("1、自定义属性")]public Color ValueFontColor{get {return _yValueFontColor; }set{_yValueFontColor = value;Refresh();}}/// <summary>/// 显示value值字体/// </summary>[Description("显示value值字体"), Browsable(true), Category("1、自定义属性")]public Font ValueFont{get {return _yValueFont; }set{_yValueFont = value;Refresh();}}