覆盖按钮上的 OnPaint - 字体不同

Overriding OnPaint on Button - Font different

我正在尝试覆盖 WinForms 按钮控件中的 OnPaint。我想在中心对齐图像和文本,彼此相邻。据我所知,使用默认控件无法做到这一点。思路是继承自Button,"override"只有图片+文字部分的绘制。我有一个几乎可以工作的版本,但是如果我在我的 ImgButton 和 Button 上设置 "Segoe UI Semibold; 9pt; style=Bold",ImgButtons 文本会多很多 "Bold"。这是我的 class:

Imports System.Windows.Forms
Imports System.Drawing

Public Class ImgButton
Inherits Button

Public Sub New()
    MyBase.New()
End Sub

Private _text As String = "Text"
Private _img As Bitmap = Nothing

Private isOwnerPainting As Boolean = True

Overrides Property Text As String
    Get
        If isOwnerPainting = True Then
            Return _text
        Else
            Return ""
        End If
    End Get
    Set(value As String)
        _text = value
    End Set
End Property

Property CenteredImage As Bitmap
    Get
        If isOwnerPainting = True Then
            Return _img
        Else
            Return Nothing
        End If
    End Get
    Set(value As Bitmap)
        _img = value
    End Set
End Property

Private _font As Font = MyBase.Font
Overrides Property Font As Font
    Get
        Return _font
    End Get
    Set(value As Font)
        _font = value
    End Set
End Property

Protected Overrides Sub OnPaint(ByVal pe As PaintEventArgs)
    isOwnerPainting = True
    If Me.CenteredImage IsNot Nothing Then
        isOwnerPainting = False
        MyBase.OnPaint(pe)
        isOwnerPainting = True
        Dim textWidth As Integer = pe.Graphics.MeasureString(Me.Text, Me.Font).Width
        Dim textHeight As Integer = pe.Graphics.MeasureString(Me.Text, Me.Font).Height

        Dim imgPlusTextWidth As Integer = Me.CenteredImage.Width + textWidth
        Dim imgPlusTextHeight As Integer = Me.CenteredImage.Height + textHeight

        Dim imageLeft As Integer = (Me.Width / 2) - (imgPlusTextWidth / 2)

        pe.Graphics.DrawImage(Me.CenteredImage, New Point(imageLeft, (Me.Height / 2) - (Me.CenteredImage.Height / 2)))

        pe.Graphics.DrawString(Me.Text, Me.Font, New SolidBrush(MyBase.ForeColor), New Point(imageLeft + 5 + Me.CenteredImage.Width, (Me.Height / 2) - (textHeight / 2)))
    Else
        isOwnerPainting = True
        MyBase.OnPaint(pe)
    End If
    isOwnerPainting = True
End Sub

End Class

感谢您的帮助。

编辑:差异图片:img(此处不能 post img)

DrawString有很多问题,所以用TextRenderer.DrawText方法代替:

TextRenderer.DrawText(pe.Graphics, Me.Text, Me.Font, ...