C#在鼠标移动时绘制折线

时间:2014-09-26 13:27:29

标签: c# xaml mouse draw move

每当 drawing_mode is_drawing 布尔开启时,我想在画布上绘制一些东西。现在我使用折线列表和BackgroundWorker进行线程化。我的主要问题是我的代码只创建了一条折线,并且点总是连接在一起。换句话说,我可以停止绘画一段时间,但是无论何时我点击与前一个连接的新线路连接。最终的结果是我的canvas.Children只有一个包含所有点的折线元素。谁能帮我解决这个问题? 附:我对线程不是很好......

    private BackgroundWorker drawing_worker;

    private void drawing_worker_ProgressChanged(object sender, ProgressChangedEventArgs eventargs)
    {            

        Polyline polyline = new Polyline();
        polyline.Points = last_polyline.Points;
        canvas.Children.Remove(last_polyline);

        var pos = canvas_relative_pos;
        polyline.Points.Add(pos);
        polyline.Stroke = new SolidColorBrush(Colors.Black);
        polyline.StrokeThickness = 1;
        canvas.Children.Add(polyline);

        last_polyline = polyline;
    }

    private void drawing_worker_DoWork(object sender, DoWorkEventArgs eventargs)
    {
        while (drawing_mode_enabled && is_drawing)
        {
            drawing_worker.ReportProgress(0);
            Thread.Sleep(5);
            if (drawing_worker.CancellationPending) break;
        }
    }

    private void ContentControl_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        if (drawing_mode_enabled)
        {
            is_drawing = true;

            drawing_worker = new BackgroundWorker
            {
                WorkerReportsProgress = true,
                WorkerSupportsCancellation = true                   
            };

            drawing_worker.ProgressChanged += drawing_worker_ProgressChanged;
            drawing_worker.DoWork += drawing_worker_DoWork;
            drawing_worker.RunWorkerAsync();
        }
    }

1 个答案:

答案 0 :(得分:0)

您不需要BackgroundWorker或任何其他异步内容来在Canvas上绘制折线。

只需创建一个带有Background的Canvas(以便获取输入事件)和MouseLeftButtonDownMouseLeftButtonUpMouseMove事件的处理程序:

<Canvas Background="Transparent"
        MouseLeftButtonDown="CanvasMouseLeftButtonDown"
        MouseLeftButtonUp="CanvasMouseLeftButtonUp"
        MouseMove="CanvasMouseMove"/>

在鼠标按下处理程序中,创建一个新的Polyline并将其添加到Canvas中。同样捕获鼠标,以便即使鼠标光标离开画布也可以获得鼠标移动事件。在鼠标向上处理程序中释放鼠标捕获。最后,在鼠标移动处理程序中,将点添加到画布的最后一个折线子项。

private void CanvasMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    var panel = (Panel)sender;
    var polyline = new Polyline
    {
        Stroke = Brushes.Black,
        StrokeThickness = 3
    };

    panel.Children.Add(polyline);
    panel.CaptureMouse();
}

private void CanvasMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
    ((UIElement)sender).ReleaseMouseCapture();            
}

private void CanvasMouseMove(object sender, MouseEventArgs e)
{
    var panel = (Panel)sender;

    if (panel.IsMouseCaptured)
    {
        var polyline = panel.Children.OfType<Polyline>().Last();
        polyline.Points.Add(e.GetPosition(panel));
    }
}