先上效果图:
背景色,前景色,字体,字号,字色,字的对齐方式都可以设置。
开始写代码:
窗体上加一个timer控件,目的是让进度条值不断增加。timer 的 interval 设置为100,并且启用.
全部窗体代码如下:
Public Class Form1
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
If MyProgressBar1.Value < 100 Then
MyProgressBar1.Value += 1
End If
End Sub
End Class
Public Class MyProgressBar
Inherits ProgressBar
Public Property CharColor As Color
Public Property CharTop As Single = 0
Public Property CharFont As Font
Public Property CharPositonType As PositionType
Public Property ShowPercent As Boolean
Public Enum PositionType
left = 0
middle = 1
right = 2
auto = 3
auto2 = 4
End Enum
Public Sub New()
CharFont = New Font("candara", 14, FontStyle.Regular)
CharPositonType = PositionType.auto
CharColor = Color.White
BackColor = Color.MediumPurple
ForeColor = Color.SlateBlue
Me.SetStyle(ControlStyles.UserPaint, True)
End Sub
Protected Overrides Sub OnPaint(e As PaintEventArgs)
Dim percentage As UInt16, x As Int16
percentage = CType((Value * 100) / Maximum, UInt16)
Dim percent_str As String = percentage & IIf(ShowPercent, "%", "")
Dim Rect As Rectangle = e.ClipRectangle
Rect.Width = CType((Rect.Width * Value / Maximum), UInt16) - 4
Rect.Height = Rect.Height - 4
e.Graphics.FillRectangle(New SolidBrush(BackColor), 0, 0, e.ClipRectangle.Width, e.ClipRectangle.Height)
e.Graphics.FillRectangle(New SolidBrush(ForeColor), 2, 2, Rect.Width, Rect.Height)
Dim myfont As New Font(CharFont.FontFamily, CharFont.Size, FontStyle.Regular)
Dim size As Size = TextRenderer.MeasureText(percent_str, myfont)
If CharPositonType = 4 Then
If Rect.Width - size.Width / 2 > 0 Then
If (Rect.Width < e.ClipRectangle.Width - size.Width / 2) Then
x = (Rect.Width - size.Width / 2)
Else
x = e.ClipRectangle.Width - size.Width - 2
End If
Else
x = 2
End If
ElseIf (CharPositonType = 3) Then
If (Rect.Width - size.Width > 0) Then
x = (Rect.Width - size.Width) / 2
Else
x = 2
End If
ElseIf CharPositonType = 2 Then
x = e.ClipRectangle.Width - size.Width - 2
ElseIf CharPositonType = 1 Then
x = (e.ClipRectangle.Width - size.Width) / 2
ElseIf CharPositonType = 0 Then
x = 2
End If
e.Graphics.DrawString(percent_str, New Font(CharFont.FontFamily, CharFont.Size, FontStyle.Regular), New SolidBrush(CharColor), New Point(x, CharTop))
MyBase.OnPaint(e)
End Sub
End Class
代码写上以后(先把timer的代码注释掉。因为这时候还没有自定义的控件),点运行,然后关闭窗体。这时候,在工具箱就能看见我们的 MyProgressBar了。拖到窗体上,timer的代码取消注释,再运行,就能看到效果了。
可以设置的属性:
- BackColor:进度条的背景色
- CharColor:文字的颜色
- CharFont:文字的字体和字号
- CharPositionType:文字对齐方式。left 居左,middle 居中间,right 居右,auto 根据进度居于进度的中间。比如如果value是50,那么left就是1/4进度条的大小。auto2 始终位于当前进度的最大处,并且文字居于其中间。关于不同的取值的效果,请见下图。
- CharTop:文字距离顶部的距离。由于不同的字体会有不同的结果,所以给出了这个属性。以便于根据字体来调整。
- ForeColor:进度条的颜色。
- ShowPercent:是否显示%这个符号 取值为false时,只显示百分数,否则显示为 xx%