Pregunta

I need to implement hit-testing for my Windows Form Control. I have my custom class which inherits the Control class and I draw, in the OnPaint method, a polyline:

e.Graphics.DrawLines(myPen, myPoints);

Now, during the MouseDown event I get the position of the mouse and I implement the hit-testing like follow:

using (var path = new GraphicsPath())
{  
   path.AddLines(myPoints);
   return path.IsVisible(pt);
}

The problem is that if have, for example, the polyline in figure (which may seem like a polygon) the IsVisible method returns true even if I click inside the region that represents this polygon:

enter image description here

I need a different behavior, the method have to return true only if I click over the line. How can I do?

¿Fue útil?

Solución

You just need to use a different method for hit-testing: IsOutlineVisible instead of IsVisible.

using (var path = new GraphicsPath())
{  
   path.AddLines(myPoints);
   return path.IsOutlineVisible(pt, Pens.Black);
}

You need to provide a pen because line-based hit-testing works with line and lines can have a specific width. That said I'd suggest to use a different (thicker) pen from what you use for drawing because to pick a single pixel with mouse isn't such easy for many many users.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top