分享

手把手教你开发圆盘仪表控件

 googplay 2024-04-26 发布于广东

前言

大家好,我是新阁教育韩工,前几天在网上看到了一个比较好看的环形控件,今天我们来尝试使用GDI+的方式来绘制一下。

图片


创建项目

自定义控件库其实本质上就是一个类库,所以我们在创建项目时直接创建类库项目。

图片

在创建好的类库项目中添加“用户控件”。

图片

实现思路

整个控件其实是由四个部分组成的。第一个部分为一个固定颜色的底圆,第二部分是一个渐变色的扇形,第三部分是一个颜色与窗体背景色相同的上圆,第四部分是显示百分比的文字。最后将这四个部分叠加起来就得到了我们最终想要得到的控件。图片

实现过程

1.绘制准备

在用户控件中添加代码,我们使用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.绘制底圆

我们在事件中继续添加一些代码,使用画布的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.绘制扇形

首先创建属性与字段,以便使用属性来控制扇形的区域,使得扇形的区域是可变的。

//最大值
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.绘制上圆

绘制上圆比较简单,大小比底圆稍小,位置在整个控件中心,颜色与控件颜色相同。

//绘制上圆
SolidBrush solidBrushElipse = new SolidBrush(this.BackColor);
Rectangle rectangle3 = new Rectangle(15, 15, this.Width - 30, this.Height - 30);
graphics.FillEllipse(solidBrushElipse, rectangle3);

测试效果如下:

图片

5.绘制文字

最后在控件的中心位置绘制文字

//绘制文字
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+的方式来绘制出一个好看的显示百分比的环形控件,希望可以给大家一些启发。

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多