如何选择CheckBoxRenderer.DrawCheckBox重载并设置各类Renderer的前景色与背景色
使用CheckBoxRenderer、TextBoxRenderer的两个关键问题解决方案
1. 选择CheckBoxRenderer.DrawCheckBox的特定重载
CheckBoxRenderer.DrawCheckBox的重载选择完全取决于你的需求场景:
- 仅绘制复选框图标:选择只包含
Graphics、Point、CheckBoxState的基础重载 - 绘制带文本的复选框:选择添加了文本、字体、文本格式参数的重载
- 绘制带自定义图标的复选框:选择包含
Image和图标绘制矩形的重载 - 示例中使用的是同时支持文本和自定义图标的重载,参数覆盖了位置、文本区域、内容、字体、图标、状态等所有核心要素,适合需要高度自定义的场景
2. 设置文本前景色与矩形背景色
TextBoxRenderer的自定义颜色处理
TextBoxRenderer的部分重载支持直接传入Color参数设置前景/背景色,如果使用的重载不支持,可通过两步实现:
- 手动填充背景:用
Graphics.FillRectangle将目标区域填充为指定背景色 - 单独绘制文本:用
TextRenderer.DrawText传入自定义前景色绘制文本,再调用TextBoxRenderer绘制边框样式
CheckBoxRenderer的自定义颜色处理
CheckBoxRenderer默认遵循系统主题,若要自定义文本颜色,需要拆分绘制步骤:
- 调用CheckBoxRenderer仅绘制复选框图标部分
- 用
TextRenderer.DrawText手动绘制文本,指定自定义前景色
示例代码
CheckBoxRenderer 实现代码
'针对CheckBoxRenderer Dim gl As Point = GC1.Location Dim r As Rectangle = GC1.ClientRect Dim textrect As New Rectangle(r.Left + 1, r.Top, r.Width - 2, r.Height) Dim s As String = GetCellString(GC1, FMT(GC1.FMTCode)) Dim fnt As Font = GetFont(GC1.Font, DefaultLabelFont) Dim flags As TextFormatFlags = GC1.TextFormatFlag Dim i As Image Dim imagerect As New Rectangle(r.Left + 1, r.Top, r.Width - 2, r.Height) Dim state As CheckBoxState = GetCheckBoxState(GC1.Enabled, GC1.CheckCellChecked, Focused) CheckBoxRenderer.DrawCheckBox(g, gl, textrect, s, fnt, flags, i, imagerect, Focused)
TextBoxRenderer 自定义颜色实现代码
'针对TextBoxRenderer Dim s As String = GC1.Value.ToString Dim fnt As Font = GC1.Font Dim r As Rectangle = GC1.ClientRect Dim fc As Color = GC1.ForeColor Dim bc As Color = GC1.BackColor Dim r2 As New Rectangle(r.Left + 1, r.Top + 1, r.Width - 2, r.Height - 2) Dim flags As TextFormatFlags = GC1.TextFormatFlag Dim state As TextBoxState = GetTextBoxState(GC1.Enabled, Focused) ' 先绘制背景色 g.FillRectangle(New SolidBrush(bc), r2) ' 绘制自定义前景色的文本 TextRenderer.DrawText(g, s, fnt, r2, fc, flags) ' 绘制文本框边框样式 TextBoxRenderer.DrawTextBox(g, r, String.Empty, fnt, r2, flags, state)
内容的提问来源于stack exchange,提问作者JimmyS38
相关产品推荐
相关产品推荐

