[英]MouseMove over DrawLine C#
我有一個班級
public class Line
{
public Point pt1 { get; set; }
public Point pt2 { get; set; }
}
建立清單
List<Line> lines = new List<Line>();
PaintEventHandler,MouseEventHandler並向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...
}
有沒有辦法檢測線路?
例如;
我需要檢測並選擇該行,並且可以刪除該行(可選)。
你可以用這樣的東西
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;
}
您將獲得從鼠標位置到線條的最近距離。
要刪除一行,請從lines
lines.RemoveRange(0,1)
其刪除(例如lines.RemoveRange(0,1)
),然后調用drawLines()
。 確保在foreach循環之前在drawLines()
Graphics.Clear()
內添加Graphics.Clear()
,以使舊行在從列表中刪除后不會停留在那里。 在使用MouseMoveLines()
之前,您可能還需要在移動任何行之前檢查鼠標是否處於按下狀態。 使用鼠標按下和鼠標釋放事件可以輕松實現這一點。 我無法使用MouseMoveLines()
的實際命中檢測和邏輯,因為我們需要的不僅僅是上下文。 這個問題似乎非常本地化,它的問題甚至還不清楚,但是我希望我以某種方式有所幫助,祝您一切順利。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.