我想在bmp中绘制一条线,该线位于PictureBox
,Graphic.DrawLine()
,我可以通过鼠标移动。我找不到任何功能来检查鼠标是否在线。我找到了很多方法来检查鼠标是否在Graphic.FillPolygon()
之上,但没有关于DrawLine()
。检查它有什么好的解决方案吗?
编辑: 所以通过这个建议我做了这样一个功能:
private bool IsPointInPolygon4(Point[] poly, Point p)
{
System.Drawing.Drawing2D.GraphicsPath test = new System.Drawing.Drawing2D.GraphicsPath();
if (poly.Length == 2) // it means there are 2 points, so it's line not the polygon
{
test.AddLine(poly[0], poly[1]);
if (test.IsVisible(p, g))
{
MessageBox.Show("You clicked on the line, congratulations", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
test.Dispose();
return true;
}
}
else
{
test.AddPolygon(poly);
if (test.IsVisible(p, g))
{
MessageBox.Show("You clicked on the polygon, congratulations", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
return true;
}
}
return false;
}
它适用于多边形。但我仍然无法获得鼠标事件。有什么建议吗?
答案 0 :(得分:2)
你不可能 over 几何线,因为它没有尺寸。你只能将一个点作为线本身的一部分,但除非你以无限精度击中它,否则这是不可能的(即使双打也不能完成这项工作)。你可以在为该线绘制的像素上,但这不一样。
您应该获取两点的几何坐标和鼠标的坐标。然后计算鼠标点与线的距离(这很简单,互联网上有很多文档)。
如果绝对距离小于一个阈值(1?1.5?2?),那么你就足够接近说“就行了”:
if (distance(px, py, qx, qy, mx, my) < 1.5)
{
// on the line
}
我将distance()
的实施留给您。
答案 1 :(得分:0)
由于你的线可以是0度和90度以外的角度,我看到2个选项。
第一种是使用Line Drawing Algorithm来计算线的点,并检查鼠标的位置与生成的坐标的位置。这种匹配可能会略微模糊&#34;如果您选择的线算法与.NET用于绘制线的算法不同。
第二个是使用包含GraphicsPath的line并在其上调用.IsVisible(point)方法,如果路径包含该点,则会返回true
。< / p>
我推荐选项2,因为它可能更容易实现,并允许您使用&#34;虚拟路径&#34;它比实际线条更粗,使用户更容易与它进行交互。