我希望能够在运行时创建自定义条带按钮。 我可以创建按钮并设置背景颜色。 该按钮是具有许多属性的自定义控件。 这不起作用,按钮没有条纹:
Private Sub EventButton_Paint(sender As Object, e As PaintEventArgs) Handles Me.Paint
If isStripy Then
e.Graphics.FillRectangle(New Drawing2D.HatchBrush(Drawing2D.HatchStyle.BackwardDiagonal, Color.WhiteSmoke, Me.BackColor), Me.Bounds)
End If
End Sub
任何建议或指导意见,
由于
答案 0 :(得分:2)
要执行此操作,您不应使用Me.Bounds
,而应使用e.ClipRectangle
。 Bounds
将为您提供相对于父控件的绑定位置。
然后您需要在Button
Paint
event
中执行两项操作才能完成任务;
绘制Button
BackColor
Dim brush As Drawing2D.HatchBrush = New Drawing2D.HatchBrush(Drawing2D.HatchStyle.BackwardDiagonal, Color.Brown, btn.BackColor)
e.Graphics.FillRectangle(brush, e.ClipRectangle()) 'Draw the background
通过重新绘制String
BackColor
Dim stringSize As SizeF = e.Graphics.MeasureString(btn.Text, btn.Font) 'Needed to redraw the text
Dim textX As Single = (e.ClipRectangle().Width - stringSize.Width) / 2 'Assuming in the centre
Dim textY As Single = (e.ClipRectangle().Height - stringSize.Height) / 2 'Assuming in the centre
e.Graphics.DrawString(btn.Text, btn.Font, New SolidBrush(btn.ForeColor), textX, textY) 'Redraw the text
例如,这就是您的代码的样子:
Imports System.Windows.Forms
Public Class Form1
Private Sub MyButton1_Paint(sender As Object, e As PaintEventArgs) Handles MyButton1.Paint
Dim btn As MyButton = TryCast(sender, MyButton)
If btn.IsStripy Then
Dim brush As Drawing2D.HatchBrush = New Drawing2D.HatchBrush(Drawing2D.HatchStyle.BackwardDiagonal, Color.Brown, btn.BackColor)
e.Graphics.FillRectangle(brush, e.ClipRectangle()) 'Draw the background
Dim stringSize As SizeF = e.Graphics.MeasureString(btn.Text, btn.Font) 'Needed to redraw the text
Dim textX As Single = (e.ClipRectangle().Width - stringSize.Width) / 2 'Assuming in the centre
Dim textY As Single = (e.ClipRectangle().Height - stringSize.Height) / 2 'Assuming in the centre
e.Graphics.DrawString(btn.Text, btn.Font, New SolidBrush(btn.ForeColor), textX, textY) 'Redraw the text
End If
End Sub
End Class
Public Class MyButton
Inherits Button
Public IsStripy As Boolean = True
End Class
你应该得到以下结果(注意按钮被剥离)