

Title  Draw a rubberband circle 
Keywords  rubberband, circle, user drawing 
Categories  Graphics 


In the form's MouseDown event handler, start dragging. Call subroutine DrawCircle to draw the circle in invert mode.
In the MouseMove event handler, redraw the circle to erase it. Update the corners defining the circle's position and call DrawCircle again to draw it in its new position.
In the MouseUp event handler, draw the circle in its final color.


Private Sub Form_MouseDown(Button As Integer, Shift As _
Integer, X As Single, Y As Single)
m_Dragging = True
DrawMode = vbInvert
X1 = X
Y1 = Y
X2 = X
Y2 = Y
DrawCircle
End Sub
Private Sub Form_MouseMove(Button As Integer, Shift As _
Integer, X As Single, Y As Single)
If Not m_Dragging Then Exit Sub
' Erase the old circle.
DrawCircle
X2 = X
Y2 = Y
' Draw the new circle.
DrawCircle
End Sub
Private Sub Form_MouseUp(Button As Integer, Shift As _
Integer, X As Single, Y As Single)
m_Dragging = False
' Draw the final circle.
DrawMode = vbCopyPen
ForeColor = vbRed
DrawCircle
ForeColor = vbBlack
End Sub


Subroutine DrawCircle draws a circle. Depending on the value of the optStart option button, the routine centers the circle at the user's original MouseDown position or centers it between that point and the current point.


Private Sub DrawCircle()
Dim cx As Single
Dim cy As Single
Dim dx As Single
Dim dy As Single
Dim radius As Single
If optStart(0).Value Then
' (X1, Y1) is the center.
cx = X1
cy = Y1
dx = X1  X2
dy = Y1  Y2
Else
' (X1, Y1) is a corner.
cx = (X1 + X2) / 2
cy = (Y1 + Y2) / 2
dx = (X1  X2) / 2
dy = (Y1  Y2) / 2
End If
radius = Sqr(dx * dx + dy * dy)
Circle (cx, cy), radius
End Sub





