如何制作条纹按钮

时间:2016-01-05 13:38:43

标签: vb.net button custom-controls

我希望能够在运行时创建自定义条带按钮。 我可以创建按钮并设置背景颜色。 该按钮是具有许多属性的自定义控件。 这不起作用,按钮没有条纹:

    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

任何建议或指导意见,

由于

1 个答案:

答案 0 :(得分:2)

要执行此操作,您不应使用Me.Bounds,而应使用e.ClipRectangleBounds将为您提供相对于父控件的绑定位置。

然后您需要在Button Paint event中执行两项操作才能完成任务;

  1. 绘制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
    
  2. 通过重新绘制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
    
  3. 例如,这就是您的代码的样子:

    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
    

    你应该得到以下结果(注意按钮被剥离)

    enter image description here