1
votes
    Dim HaveToDraw As New Boolean
    Dim xMouse As Integer
    Dim yMouse As Integer

    Private Sub foo(sender As Object, e As PaintEventArgs) Handles PictureBox1.Paint
        If HaveToDraw = True Then
            e.Graphics.FillEllipse(Brushes.Green, xMouse, yMouse, 10, 10)
        End If
        HaveToDraw = False
    End Sub

    Sub PictureBox1_MouseClick(sender As Object, e As MouseEventArgs) Handles PictureBox1.MouseClick
        If RadioButton1.Checked = True Then
            xMouse = e.X
            yMouse = e.Y
            HaveToDraw = True
            PictureBox1.Refresh()
        End If
    End Sub

This code lets the user draw an elipse when he clicks on any point on the map, but there are 2 problems with it: 1 - The user is able to draw only one elipse; 2 - The user is not able to erase a previously created elipse.

So, how can I do that solving these two problems?

1
To have multiple points, use a List(Of Point) and store each click in there. In the the Paint() event, iterate over your List and draw each Point. To erase a previous created ellipse you can trap a Right click on the Map and check for a "hit" against points in your List. Even better, if a "hit" is found, display a context menu with a Delete option in it. Make sure your "hit" takes into account the size of the ellipse. You can use a standard point to point distance formula.Idle_Mind

1 Answers

2
votes

As @Idle_Mind suggested, you could use a list to store your points, and a right-click event to remove the points:

Dim radius as Integer = 5
Private points As New List(Of Point)()
Private Sub pictureBox1_MouseClick(sender As Object, e As MouseEventArgs)
    If e.Button = System.Windows.Forms.MouseButtons.Left Then
        points.Add(e.Location) ' add point on left click
    ElseIf e.Button = System.Windows.Forms.MouseButtons.Right Then 
        For i As Integer = 0 To points.Count - 1 ' remove points on right-click
            If distance(points(i).X, points(i).Y, e.Location) < radius Then
                points.RemoveAt(i)
            End If
        Next
    End If
    pictureBox1.Refresh()
End Sub


'helper function
Private Function distance(x__1 As Integer, y__2 As Integer, mousep As Point) As Integer
    Dim X__3 As Integer = CInt(Math.Pow(CDbl(x__1 - mousep.X), 2))
    Dim Y__4 As Integer = CInt(Math.Pow(CDbl(y__2 - mousep.Y), 2))

    Return CInt(Math.Sqrt(CDbl(X__3 + Y__4)))
End Function

Private Sub pictureBox1_Paint(sender As Object, e As PaintEventArgs)
    For i As Integer = 0 To points.Count - 1
        e.Graphics.FillEllipse(Brushes.Green, points(i).X - radius, points(i).Y - radius, radius * 2, radius * 2)
    Next
End Sub

I also changed the paint code to draw the circles so that they are centered under the mouse-click.