MouseMove在DrawLine C#上

时间:2015-09-08 08:20:40

标签: c# .net drawing

我有一个线类

public class Line
{
    public Point pt1 { get; set; }
    public Point pt2 { get; set; }
}

创建了一个列表

List<Line> lines = new List<Line>();

PaintEventHandler,MouseEventHandler&amp;在Form()

中为列表添加点
this.Paint += new PaintEventHandler(DrawLines);
this.MouseMove += new MouseEventHandler(MouseMoveLines);

lines.Add(new Line()
{
    pt1 = new Point(3, 3),
    pt2 = new Point(120, 120)
});

然后我要绘制线条。

private void DrawLines(object sender, PaintEventArgs e)
{
    foreach (Line l in lines)
    {
        e.Graphics.DrawLine(Pens.Black, l.pt1, l.pt2);
    }
}

private void MouseMoveLines(object sender, MouseEventArgs e)
{
    // I need some magic...
}

有没有办法检测线?

例如;

我需要检测并选择该行,并且可以选择删除该行。

2 个答案:

答案 0 :(得分:0)

你可以使用类似的东西

public static double GetDistanceBetweenLineAndPoint(this MathDefinitions.Vector2 point, MathDefinitions.Vector2 linePoint1, MathDefinitions.Vector2 linePoint2)
{
    var direction = (linePoint2 - linePoint1);
    var normalizedCopy = direction.NormalizedCopy;
    double len = direction.Length;
    if (len < float.Epsilon) return (point - linePoint1).Length;
    var delta1 = point - linePoint1;
    var delta2 = point - linePoint2;
    double t = delta1.NormalizedCopy.Dot(normalizedCopy);
    if (t <= 0.0) return delta1.Length;
    double t2 = delta2.NormalizedCopy.Dot(normalizedCopy);
    if (t2 >= 0.0) return delta2.Length;
    MathDefinitions.Vector2 proj = linePoint1 + (t * delta1.Length) * normalizedCopy;
    return (point - proj).Length;
}

您将获得距离鼠标位置最近的距离。

答案 1 :(得分:0)

要删除一行,请将其从lines中删除(例如lines.RemoveRange(0,1)),然后重新调用drawLines()。确保在foreach循环之前在Graphics.Clear()内添加drawLines(),以便旧行在从列表中删除后不会留在那里。在使用MouseMoveLines()之前,您可能还想在移动任何线条之前检查鼠标是否已关闭。使用鼠标按下和鼠标释放事件可以轻松实现这一点。我无法使用MouseMoveLines()的实际命中检测和逻辑,因为我们需要的不仅仅是上下文。这个问题似乎非常局部化,它的问题甚至不是很清楚,但我希望我能以某种方式帮助你,并祝你好运,不管你做什么。< / p>