/// <summary>
/// 按下鼠标左键移动
/// </summary>
private void Canvas_PreviewMouseMove(object sender, MouseEventArgs e)
{
if (e.LeftButton == MouseButtonState.Pressed)
{
// 返回指针相对于Canvas的位置
Point point = e.GetPosition(myCanvas);
if (pointList.Count == 0)
{
// 加入起始点
pointList.Add(new Point(this.startPoint.X, this.startPoint.Y));
}
else
{
// 加入移动过程中的point
pointList.Add(point);
}
// 去重复点
var disList = pointList.Distinct().ToList();
var count = disList.Count(); // 总点数
if (point != this.startPoint && this.startPoint != null)
{
var l = new Line();
string color = (cboColor.SelectedItem as ComboBoxItem).Content as string;
if (color == "默认")
{
l.Stroke = Brushes.Black;
}
if (color == "红色")
{
l.Stroke = Brushes.Red;
}
if (color == "绿色")
{
l.Stroke = Brushes.Green;
}
l.StrokeThickness = 1;
if (count < 2)
return;
l.X1 = disList[count - 2].X; // count-2 保证 line的起始点为点集合中的倒数第二个点。
l.Y1 = disList[count - 2].Y;
// 终点X,Y 为当前point的X,Y
l.X2 = point.X;
l.Y2 = point.Y;
myCanvas.Children.Add(l);
}
}
}
移动过程中创建Line对象并加入Canvas中。 代码中的颜色判断最好修改成枚举类型。