我想用Graphic.DrawLine()在PictureBox中的bmp中画一条线,我可以用鼠标移动它。我找不到任何功能来检查鼠标是否在线。我找到了许多方法来检查鼠标是否在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;
}它对多边形非常有效。但是我还是不能让鼠标事件在线上。有什么建议吗?
发布于 2016-04-16 07:18:20
你永远不能超过一条几何线,因为它没有尺寸。你只能让一个点成为直线本身的一部分,但这是不可能的,除非你以无限的精度命中它(在这里,即使是双倍精度也做不到这项工作)。你可以在为这条线绘制的像素上,但这是不同的。
您应该获取两个点的几何坐标和鼠标的坐标。然后计算鼠标指针到直线的距离(这很简单,在Internet上有很多关于这方面的文档)。
如果绝对距离小于阈值(1? 1.5? 2?)然后你就可以说"on the line“了:
if (distance(px, py, qx, qy, mx, my) < 1.5)
{
// on the line
}我将distance()的实现留给您。
发布于 2016-04-16 03:11:56
因为你的直线可以是0度和90度以外的角度,我看到了两个选择。
第一种方法是使用Line Drawing Algorithm计算直线的点,并检查鼠标的位置和生成的坐标。如果您选择的线条算法与.NET用于绘制线条的算法不同,则此匹配可能会有一点“模糊”。
第二种方法是使用包含line的GraphicsPath并对其调用.IsVisible(point)方法,如果路径包含该点,该方法将返回true。
我推荐选择2,因为它可能更容易实现,并允许您使用比实际行更粗的“虚拟路径”,使您的用户更容易与其交互。
https://stackoverflow.com/questions/36654929
复制相似问题