WinForms Button 컨트롤에서 OnPaint를 재정의하려고합니다. 이미지와 텍스트를 가운데에, 서로 옆에 정렬하고 싶습니다. 내가 알고있는 것처럼 기본 컨트롤을 사용하여이 작업을 수행 할 수있는 방법은 없습니다. 아이디어는 Button에서 상속 받고 이미지 + 텍스트 부분의 그림 만 "덮어 쓰는"것입니다. 거의 작동하는 버전이 있지만 ImgButton 및 Button에 "Segoe UI Semibold; 9pt; style = Bold"로 설정하면 ImgButtons 텍스트가 훨씬 더 "굵게"됩니다. 수업은 다음과 같습니다.Button - Font에서 OnPaint 무시 다른
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는
하는 경우 가능한 경우 차이점의 스크린 샷이 도움이 될 수 있습니다. 다른 글꼴/스타일이 그래픽 객체의 다른 AntiAlias / ClearType 설정에 의해 발생할 수 있습니다. – hometoast
[TextRenderingHint] (https://msdn.microsoft.com/en-us/library/system.drawing.graphics.textrenderinghint) 일 수 있습니다. (v = vs.110) .aspx) –
DrawString 대신 TextRenderer.DrawText를 사용하십시오. 그것이 바로 버튼이 사용하는 것입니다. – LarsTech