|
|
Title | Draw a bar gauge |
Keywords | bar gauge |
Categories | Graphics |
|
|
Use a PictureBox control. When the form loads, give the PictureBox an interesting background.
|
|
Private Dragging As Boolean
Private NeedleX As Single
Private BarWidth As Single
Private BarHeight As Single
Private Sub Form_Load()
Dim i As Integer
Dim clr As Integer
Dim dclr As Single
Dim hgt As Single
' Give the slider an interesting background.
Picture1.ScaleMode = vbPixels
dclr = 256 / Picture1.ScaleWidth
hgt = Picture1.ScaleHeight
For i = 0 To Picture1.ScaleWidth
clr = i * dclr
Picture1.Line (i, 0)-(i, hgt), RGB(0, 0, clr)
Next i
' Save some useful values for later.
BarWidth = Picture1.ScaleWidth
BarHeight = Picture1.ScaleHeight
' Prepare Picture1.
Picture1.DrawMode = vbInvert
Picture1.DrawWidth = 2
End Sub
|
|
In the PictureBox's MouseDown event handler, start the drag. If there is a line on the PictureBox, draw it again in invert mode to erase it. Then update the line's position and draw it again.
|
|
Private Sub Picture1_MouseDown(Button As Integer, Shift As _
Integer, X As Single, Y As Single)
Static done_before As Boolean
Dragging = True
' Erase the previous line if there is one.
If done_before Then
Picture1.Line (NeedleX, 0)-(NeedleX, BarHeight)
Else
done_before = True
End If
' Update NeedleX.
NeedleX = X
If NeedleX < 0 Then
NeedleX = 0
ElseIf NeedleX > BarWidth Then
NeedleX = BarWidth
End If
' Draw the new line.
Picture1.Line (NeedleX, 0)-(NeedleX, BarHeight)
' Display the value.
DisplayValue
End Sub
|
|
In the MouseMove event handler, erase the previous line and draw a new one.
|
|
Private Sub Picture1_MouseMove(Button As Integer, Shift As _
Integer, X As Single, Y As Single)
If Not Dragging Then Exit Sub
' Erase the old line.
Picture1.Line (NeedleX, 0)-(NeedleX, BarHeight)
' Update NeedleX.
NeedleX = X
If NeedleX < 0 Then
NeedleX = 0
ElseIf NeedleX > BarWidth Then
NeedleX = BarWidth
End If
' Draw the new line.
Picture1.Line (NeedleX, 0)-(NeedleX, BarHeight)
' Display the value.
DisplayValue
End Sub
|
|
In the MouseUp event handler, stop dragging.
|
|
Private Sub Picture1_MouseUp(Button As Integer, Shift As _
Integer, X As Single, Y As Single)
Dragging = False
End Sub
Private Sub DisplayValue()
Label1.Caption = _
Format$(CInt((NeedleX / BarWidth) * 100))
End Sub
|
|
|
|
|
|