如何在用户点击地图时绘制点数

时间:2014-02-25 16:11:19

标签: vb.net draw

    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

此代码允许用户在点击地图上的任何点时绘制一个椭圆,但它有两个问题:1 - 用户只能绘制一个椭圆; 2 - 用户无法删除先前创建的椭圆。

那么,我怎样才能解决这两个问题呢?

1 个答案:

答案 0 :(得分:2)

正如@Idle_Mind建议的那样,您可以使用列表来存储积分,并使用right-click事件来删除积分:

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)
                Exit Sub
            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

我还更改了绘画代码以绘制圆圈,以便它们在鼠标单击下居中。 HTH