前言
所以,在之前的文章中,有针对DataGridView的选择框做过一次重绘;这一篇就单独用来重绘下这两个控件,即RadioButton和CheckBox。.
开发环境:.NET Framework版本:4.8
开发工具:Visual Studio 2022
实现步骤
-
首先去找四个好看的图标,分别对应
RadioButton和CheckBox的选中/未选中状态(当然不想用图片也可以,比如自己画框或者使用图标库),然后将这些图片加入到资源文件中。 -
创建自定义控件,定义
Checked属性
private bool _checked = false;public bool Checked { get { return _checked; } set { _checked = value; Invalidate(); }
-
重写
OnPaint事件,做以下处理rotected override void OnPaint(PaintEventArgs e){base.OnPaint(e);e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;e.Graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;e.Graphics.CompositingQuality = CompositingQuality.HighQuality;e.Graphics.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;SizeF textSize = e.Graphics.MeasureString(Text, Font);SizeF imgSize = new SizeF(textSize.Height, textSize.Height);float imgX = 5, imgY = (Height - imgSize.Height) / 2;e.Graphics.DrawImage(Checked ? Properties.Resources.Check_check : Properties.Resources.Check_normal, imgX, imgY, imgSize.Width, imgSize.Height);float textX = imgX + imgSize.Width + 5, textY = (Height - textSize.Height) / 2 + 2;e.Graphics.DrawString(Text, Font, new SolidBrush(ForeColor), textX, textY);}
-
重写
OnClick事件protected override void OnClick(EventArgs e){base.OnClick(e);Checked = !Checked;}
-
针对单选情况需要特殊处理,即在同一个容器中的时候,只能选中一个,所以
RadioButton的OnClick事件如下protected override void OnClick(EventArgs e){base.OnClick(e);SetChecked();}private void SetChecked(){Checked = !Checked;if (Parent != null && !(Parent is Form)){foreach (Control control in Parent.Controls){if (control is RadioEx radio){radio.Checked = false;}}Checked = true;}}
-
从
OnPaint事件中可以看到,选择框的大小是随着字体大小而调整的,所以只需要修改Font的属性即可
实现效果
