Use a form-level variable to indicate whether the program is drawing the star.
In the MouseDown event handler, start drawing in vbInvert mode.
In the MouseMove event handler, if we are drawing then erase the previous star and
draw the new one.
In the MouseUp event handler, stop drawing and make the star permanent.
The DrawShape subroutine separates the drawing from the mouse interactions
so it is easy to change the rubberband shape.
|
Option Explicit
Private m_Drawing As Boolean
Private m_X1 As Single
Private m_Y1 As Single
Private m_X2 As Single
Private m_Y2 As Single
' Start drawing.
Private Sub picCanvas_MouseDown(Button As Integer, Shift As _
Integer, X As Single, Y As Single)
If Button And vbRightButton Then
' It's the right button. Cancel the draw.
If m_Drawing Then
' Erase the previous shape.
DrawShape
' Stop drawing.
m_Drawing = False
picCanvas.DrawMode = vbCopyPen
picCanvas.DrawStyle = vbSolid
End If
Else
' Start drawing.
m_Drawing = True
picCanvas.DrawMode = vbInvert
picCanvas.DrawStyle = vbDot
m_X1 = X
m_Y1 = Y
m_X2 = X
m_Y2 = Y
' Draw the first shape.
DrawShape
End If
End Sub
' Continue drawing.
Private Sub picCanvas_MouseMove(Button As Integer, Shift As _
Integer, X As Single, Y As Single)
' Do nothing if we're not drawing.
If Not m_Drawing Then Exit Sub
' Erase the previous shape.
DrawShape
' Save the new point.
m_X2 = X
m_Y2 = Y
' Draw the new shape.
DrawShape
End Sub
' Finish drawing.
Private Sub picCanvas_MouseUp(Button As Integer, Shift As _
Integer, X As Single, Y As Single)
' Do nothing if we're not drawing.
If Not m_Drawing Then Exit Sub
' Erase the previous shape.
DrawShape
' Stop drawing.
m_Drawing = False
picCanvas.DrawMode = vbCopyPen
picCanvas.DrawStyle = vbSolid
' Save the new point.
m_X2 = X
m_Y2 = Y
' Make the shape permanant. This might involve saving
' coordinates to a database or something. In this case,
' it just means redrawing the shape in non-invert mode.
DrawShape
End Sub
' Draw the shape in the area defined by the points
' (m_X1, m_Y1) and (m_X2, m_Y2).
Private Sub DrawShape()
Const PI = 3.14159265
Dim cx As Single
Dim cy As Single
Dim wid As Single
Dim hgt As Single
Dim theta As Single
Dim dtheta As Single
Dim i As Integer
cx = (m_X1 + m_X2) / 2
cy = (m_Y1 + m_Y2) / 2
wid = Abs(m_X1 - m_X2) / 2
hgt = Abs(m_Y1 - m_Y2) / 2
If wid = 0 Or hgt = 0 Then Exit Sub
' Calculate and connect the star's points.
theta = 90 * PI / 180
dtheta = 2 * 72 * PI / 180
picCanvas.CurrentX = cx + wid * Cos(theta)
picCanvas.CurrentY = cy - hgt * Sin(theta)
For i = 1 To 5
theta = theta + dtheta
picCanvas.Line -(cx + wid * Cos(theta), cy - hgt * _
Sin(theta))
Next i
End Sub
|