SqueakinSweep
Programmer
We had a thread a few months back, where someone wanted a clickable Map. Rick came up with a cracking solution for that by using a gradient background image onto which the mouse click was transposed to work out where the click was made. I have always wanted however to figure out how it was possible to determine if a mouse click was inside a user drawn polygon. There are mathematical approaches to this solution, but after a little playing around and research, I realised that .Net had this facility built in after all. The following code will show how this is done.
All that is on the form is a picturebox which is named mapdraw. Any click inside the drawn polygon will activate a Messagebox.
Sweep
...if it works dont f*** with it
...if its f****ed blame someone else
...if its your fault that its f***ed, say and admit nothing.
All that is on the form is a picturebox which is named mapdraw. Any click inside the drawn polygon will activate a Messagebox.
Code:
Imports System.Drawing
Dim WASHINGTON As PointF()
Private Sub formGraphics_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Defines new bitmap
Dim states As Bitmap = New Bitmap(mapdraw.Width, mapdraw.Height)
'Draws image to Picturebox
Me.mapdraw.Image = states
'Define graphics holder
Dim g As Graphics = Graphics.FromImage(states)
WASHINGTON = New PointF() { _
New PointF(95, 35), _
New PointF(82, 72), _
New PointF(93, 78), _
New PointF(92, 88), _
New PointF(158, 110), _
New PointF(177, 63), _
New PointF(113, 35), _
New PointF(112, 46) _
}
Dim p As New Pen(Color.Blue)
g.DrawPolygon(p, WASHINGTON)
End Sub
Private Sub mapdraw_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles mapdraw.MouseDown
If Me.PolyGonHitTest(sample, New PointF(e.X, e.Y)) Then
MsgBox("IN")
End If
End Sub
Public Function PolyGonHitTest(ByVal polygonPoints() As PointF, ByVal mousePos As PointF) As Boolean
Dim path As New System.Drawing.Drawing2D.GraphicsPath
path.AddLines(polygonPoints)
Dim region As New Region(path)
' Hittest the region to verify if the point is in the Polygon
If region.IsVisible(mousePos) Then Return True
Return False
End Function
Sweep
...if it works dont f*** with it
...if its f****ed blame someone else
...if its your fault that its f***ed, say and admit nothing.