
1.vs2019新建窗体项目
2.右键单击项目名称,选择添加->用户控件

3.命名为CircleControl,选择添加
4.右键单击我们的自定义控件,选择查看代码

5.添加以下属性
- ///
- /// 中心颜色
- ///
- private Color centerColor = Color.White;
- ///
- /// 中心颜色
- ///
- public Color CenterColor
- {
- set
- {
- centerColor = value;
- }
- get
- {
- return centerColor;
- }
- }
-
- ///
- /// 边缘颜色
- ///
- private Color edgeColor = Color.Yellow;
- ///
- /// 边缘颜色
- ///
- public Color EdgeColor
- {
- get
- {
- return edgeColor;
- }
- set
- {
- edgeColor = value;
- }
- }
-
- ///
- /// 中心点
- ///
- private PointF centerPoint = new PointF(3.5f, 3.5f);
-
- ///
- /// 中心点横坐标
- ///
- public float CenterX
- {
- set
- {
- centerPoint.X = value;
- }
- get
- {
- return centerPoint.X;
- }
- }
-
- ///
- /// 中心点纵坐标
- ///
- public float CenterY
- {
- set
- {
- centerPoint.Y = value;
- }
- get
- {
- return centerPoint.Y;
- }
- }
6.重写OnLayout事件
- ///
- /// 布局更改事件
- ///
- ///
- protected override void OnLayout(LayoutEventArgs e)
- {
- base.OnLayout(e);
-
- GraphicsPath path = new GraphicsPath();
- path.AddEllipse(new RectangleF(0f, 0f, ClientSize.Width * 1.0f, ClientSize.Height * 1.0f));
- PathGradientBrush brush = new PathGradientBrush(path);
- brush.CenterColor = centerColor;
- brush.SurroundColors = new Color[] { edgeColor };
- brush.WrapMode = WrapMode.TileFlipXY;
- brush.CenterPoint = centerPoint;
-
- Bitmap bitmap = new Bitmap(ClientSize.Width, ClientSize.Height);
- Graphics g = Graphics.FromImage(bitmap);
- g.SmoothingMode = SmoothingMode.AntiAlias;
- g.InterpolationMode = InterpolationMode.HighQualityBicubic;
- g.CompositingQuality = CompositingQuality.HighQuality;
- g.FillPath(brush, path);
- g.DrawArc(new Pen(BackColor, 4), new RectangleF(0, 0, ClientSize.Width, ClientSize.Height), 0, 360);
- BackgroundImage = bitmap;
- }
7.构造方法中开启双缓冲
- ///
- /// 构造函数
- ///
- public CircleControl()
- {
- DoubleBuffered = true;
- InitializeComponent();
- }
8.重新生成解决方案

9.回到Form1窗体,在工具箱里可以看到我们的自定义控件已经加载完毕,将其拖到Form1窗体中,并按自己风格修改圆形尺寸和中心点位置,渐变颜色等,即可运行。
避免闪屏【开启双缓冲】
DoubleBuffered = true;
避免PathGradientBrush的锯齿效果,在其外围画一个环【环的厚度刚好把锯齿填完就好】,圈的锯齿效果可以通过修改Graphics对象三个属性解决
- Graphics g = Graphics.FromImage(bitmap);
- g.SmoothingMode = SmoothingMode.AntiAlias;
- g.InterpolationMode = InterpolationMode.HighQualityBicubic;
- g.CompositingQuality = CompositingQuality.HighQuality;
中心点大约在宽高的35%~40%之间看起来效果比较自然【个人认为】
请登录码云进行下载