如何绘制带有标题的水平分隔线?

时间:2019-03-27 02:55:11

标签: winforms controls

我需要在视觉上分隔表单上的各个区域,GroupBox控件对于所需的外观来说有点“沉重”。我还需要为每个分隔符加上标题标签。

我发现了多种方法可以部分完成此操作,最流行的方法是将something like thisLabel控件一起使用:

  1. 将Label控件添加到表单中
  2. 将标签文本设置为空
  3. 将BorderStyle设置为Fixed3D
  4. 将AutoSize设置为false
  5. 将“高度”设置为2

但是,像这样的技术不允许我们指定任何用作分隔符标题的文本。

如何创建一个分隔符控件,该控件还显示其Text属性的值?

1 个答案:

答案 0 :(得分:1)

我已经可以使用自定义控件来完成此操作。在设计时和运行时都看起来像这样:

Separator Control

代码如下:

Partial Public Class Line
  Inherits Control

  Private Sub Line_Paint(Sender As Line, e As PaintEventArgs) Handles Me.Paint
    Dim oBackground As Rectangle
    Dim oTextSize As Size

    Dim _
      iX,
      iY As Integer

    oTextSize = TextRenderer.MeasureText(Me.Text, Me.Font)

    Me.Height = oTextSize.Height + 3
    iX = 1
    iY = Me.Height / 2

    Using oPen As New Pen(Me.LineColor)
      e.Graphics.DrawLine(oPen, iX, iY, Me.Width - iX - 1, iY)
    End Using

    Using oPen As New Pen(Color.White)
      e.Graphics.DrawLine(oPen, iX + 1, iY + 1, Me.Width - iX, iY + 1)
    End Using

    If oTextSize.Height > 0 Then
      Using oBrush As New SolidBrush(Me.BackColor)
        oBackground = New Rectangle(7, 1, oTextSize.Width - 2, oTextSize.Height)
        e.Graphics.FillRectangle(oBrush, oBackground)
      End Using

      Using oBrush As New SolidBrush(Me.ForeColor)
        e.Graphics.DrawString(Me.Text, Me.Font, oBrush, 7, 1)
      End Using
    End If
  End Sub



  <DefaultValue(GetType(Color), "System.Drawing.SystemColors.ActiveBorder")>
  <Description("The color of the line.")>
  <Browsable(True)>
  <Category("Appearance")>
  Public Property LineColor As Color
    Get
      Return Me._LineColor
    End Get
    Set(Value As Color)
      Me._LineColor = Value
      Me.Invalidate()
    End Set
  End Property
  Private Property _LineColor As Color = SystemColors.ActiveBorder
End Class