面。
在Windows的编程中,绘制图形时需要用到笔、画笔等对象,要书写文本,就需要字体对象。下面OnPaint方法中的代码创建了一个宽度为4的System.Drawing.Pen对象:
Dim penWidth As Integer = 4
Dim pen As Pen = New Pen(Color.Black, 4)
然后再创建一个高度为10的Arial Font对象:
Dim fontHeight As Integer = 10
Dim font As Font = New Font("Arial", fontHeight)
我们要作的最后一步的准备工作是实例化一个SolidBrush对象,并使其颜色与backgroundColor字段的颜色一致。
Dim brush As SolidBrush = New SolidBrush(backgroundColor)
现在我们就可以来画了。对于控制的底部,我们可以使用Graphics类的FillEllipse方法,圆的高和宽与控件的高和宽是相同的:
graphics.FillEllipse(brush, 0, 0, Width, Height)
然后,我们可以实例化另一个画笔,用来完成对文本的绘制:
Dim textBrush As SolidBrush = New SolidBrush(Color.Black)
至于圆形,我们可以使用Graphics类的DrawEllipse方法:
graphics.DrawEllipse(pen, Cint(penWidth/2), _
CInt(penWidth/2), Width - penWidth, Height - penWidth)
最后,我们使用DrawString方法在Graphics对象上绘制文本内容:
graphics.DrawString(Text, font, textBrush, penWidth, _
Height / 2 - fontHeight)
我们最后得到的RoundButton控件如下图所示
图:picture1
好了,把控件的代码编译为一个.DLL文件,它就可以供我们随时使用了。
表2中的代码是一个调用了RoundButton控件、名称为MyForm的表单。
表2:RoundButton控件的调用
Public Class MyForm
Inherits System.Windows.Forms.Form
#Region " Windows Form Designer generated code "
Private WithEvents roundButton As RoundButton
Public Sub New()
MyBase.New()
''这个调用是Windows Form Designer所要求的
InitializeComponent()
''在InitializeComponent()调用后,可以添加任意的实例化代码
End Sub
''表单覆盖,整理组件列表
Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
If disposing Then
If Not (components Is Nothing) Then
components.Dispose()
End If
End If
MyBase.Dispose(disposing)
End Sub
''Windows Form Designer所要求的
Private components As System.ComponentModel.IContainer
''注意:下面的过程是Windows Form Designer所要求的,
''可以使用Windows Form Designer对它进行修改,
''但不要使用软件编辑
程序进行修改
Private Sub InitializeComponent()
''
''MyForm
''
Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
Me.ClientSize = New System.Drawing.Size(292, 273)
Me.Name = "MyForm"
Me.Text = "Using Custom Control"
roundButton = New RoundButton()
AddHandler roundButton.Click, AddressOf roundButton_Click
roundButton.Text = "Click Here!"
roundButton.BackgroundColor = System.Drawing.Color.White
roundButton.Size = New System.Drawing.Size(80, 80)
roundButton.Location = New System.Drawing.Point(100, 30)
Me.Controls.Add(roundButton)
End Sub
#End Region
Private Sub roundButton_Click(ByVal source As Object, ByVal e As EventArgs)
MessageBox.Show("Thank you.")
End Sub
Public Shared Sub Main()
Dim form As MyForm = New MyForm()
Application.Run(form)
End Sub
End Class
在InitializeComponent方法中,表单对一个RoundButton对象进行实例化,并将RoundButton控件的Click事件与事件处理
程序roundButton_Click连接起来:
roundButton = New RoundBut