大家好,我是新阁教育韩工,前几天在网上看到了一个比较好看的环形控件,今天我们来尝试使用GDI+的方式来绘制一下。
创建项目上位机自定义控件库其实本质上就是一个类库,所以我们在创建项目时直接创建类库项目。
在创建好的类库项目中添加“用户控件”。
实现思路整个控件其实是由四个部分组成的。第一个部分为一个固定颜色的底圆,第二部分是一个渐变色的扇形,第三部分是一个颜色与窗体背景色相同的上圆,第四部分是显示百分比的文字。最后将这四个部分叠加起来就得到了我们最终想要得到的控件。
实现过程 1.绘制准备C#代码实现:在用户控件中添加代码,我们使用OnPaint事件来绘制控件,通过参数 e 来获取画布。并给画布设置一些属性。
protected override void onPaint(PaintEventArgs e)
{
base.onPaint(e);
// 获取画布
Graphics graphics = e.Graphics;
//消除锯齿
graphics.SmoothingMode = SmoothingMode.AntiAlias;
//文字显示效果
graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
//插补模式
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
//图片呈现质量
graphics.CompositingQuality = CompositingQuality.HighQuality;
}
2.绘制底圆
C#代码:我们在事件中继续添加一些代码,使用画布的FillEllipse()方法绘制一个底圆,底圆的大小依照整个控件的大小创建。
// 绘制底圆 SolidBrush brush1 = new SolidBrush(Color.FromArgb(93, 107, 153)); Rectangle rectangle1 = new Rectangle(1, 1, this.Width - 2, this.Height - 2); graphics.FillEllipse(brush1, rectangle1);
测试效果如下:
3.绘制扇形C#代码实现:首先创建属性与字段,以便使用属性来控制扇形的区域,使得扇形的区域是可变的。
//最大值
private float maxValue = 100;
public float MaxValue
{
get { return maxValue; }
set
{
maxValue = value;
this.Invalidate();
}
}
//实际值
private float acturevalue = 60;
public float Acturevalue
{
get { return acturevalue; }
set
{
acturevalue = value;
this.Invalidate();
}
}
//文字显示值
private float PercentVal = 0;
绘制扇形的大小与底圆的大小相一致,颜色采用渐变色。
//绘制扇形 Rectangle rectangle2 = new Rectangle(1, 1, this.Width - 2, this.Height - 2); LinearGradientBrush brush2 = new LinearGradientBrush(rectangle2, Color.Blue, Color.Red, 150.0f, true); this.PercentVal = (Acturevalue / MaxValue) * 100; graphics.FillPie(brush2, rectangle2, -90, (Acturevalue / MaxValue) * 360f);
测试效果如下:
4.绘制上圆C#代码实现:绘制上圆比较简单,大小比底圆稍小,位置在整个控件中心,颜色与控件颜色相同。
//绘制上圆 SolidBrush solidBrushElipse = new SolidBrush(this.BackColor); Rectangle rectangle3 = new Rectangle(15, 15, this.Width - 30, this.Height - 30); graphics.FillEllipse(solidBrushElipse, rectangle3);
测试效果如下:
5.绘制文字C#代码实现:最后在控件的中心位置绘制文字
//绘制文字
Font font = new Font("华为宋体", 14);
PointF point = new PointF(((float)this.Width) / 2.0f - 27, ((float)this.Height) / 2.0f - 10);
graphics.DrawString(this.PercentVal.ToString("0.0") + "%", font, Brushes.Coral, point);
测试效果如下:
总结经过大致五个步骤就可以使用GDI+的方式来绘制出一个好看的显示百分比的环形控件,希望可以给大家一些启发。
-END-
我是新阁教育韩老师,用我的专业,实现你的梦想!



