【问题标题】:Overriding OnPaint on Button - Font different覆盖按钮上的 OnPaint - 字体不同
【发布时间】:2015-01-27 18:05:00
【问题描述】:

我正在尝试在 WinForms 按钮控件中覆盖 OnPaint。我想将图像和文本对齐在中心,彼此相邻。据我所知,使用默认控件无法做到这一点。这个想法是继承自Button,并且仅“覆盖”图像+文本部分的绘制。我有一个几乎可以工作的版本,但如果我在我的 ImgButton 和 Button 上设置“Segoe UI Semibold; 9pt; style=Bold”,ImgButtons 文本会更加“粗体”。这是我的课:

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(无法在此处发布 img)

【问题讨论】:

  • 如果可能的话,差异的屏幕截图可能会有所帮助。图形对象上不同的 AntiAlias/ClearType 设置可能导致相同的字体/样式看起来不同
  • 使用 TextRenderer.DrawText 代替 DrawString。这就是按钮的用途。
  • TextRenderer.DrawText 解决了这个问题。非常感谢。

标签: vb.net winforms overriding onpaint


【解决方案1】:

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

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

【讨论】:

  • 这只是问题的一小部分。他的 Font 属性搞砸了,它不会更新 InitializeComponent()。可能是因为它没有设置 MyBase.Font。所以它重置为 Microsoft Sans,这要薄得多。
  • 是的。我正在寻找一些解决方法。覆盖字体属性已被删除,我又回到了继承的那个。 Text 属性可以在不绘制文本的情况下使用 MyBase.OnPaint。
猜你喜欢
  • 2010-10-18
  • 1970-01-01
  • 2010-12-03
  • 1970-01-01
  • 1970-01-01
  • 2018-10-02
  • 2018-05-01
  • 2017-02-24
  • 1970-01-01
相关资源
最近更新 更多