【问题标题】:How to draw a line by the mouse move with C#C#如何通过鼠标移动画线
【发布时间】:2011-11-15 15:44:38
【问题描述】:

我想通过鼠标移动在 wpf 的画布上画一条线。从一个特定的形状开始并按下鼠标左键,我想在鼠标移动的地方精确地画一条线。为此,我添加了以下代码行中详细描述的三个事件处理程序:

private void output_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        Console.WriteLine(parentCanvas.Name);
        Console.ReadLine();
        isMouseDragging = true;
      /*    rectCanvas.MouseLeftButtonDown -= new MouseButtonEventHandler(Canvas_MouseLeftButtonDown);
        rectCanvas.MouseLeftButtonUp -= new MouseButtonEventHandler(Canvas_MouseLeftButtonUp);
        rectCanvas.MouseMove -= new MouseEventHandler(Canvas_MouseMove);  */

->       parentCanvas.MouseMove += new MouseEventHandler(output_MouseMove);


    }


  private void output_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
    {
        isMouseDragging = false;

    }

    private void output_MouseMove(object sender, MouseEventArgs e)
    {
        if (isMouseDragging && e.LeftButton == MouseButtonState.Pressed)
        {
            connection_Line = new Polyline();
            connection_Line.Stroke = System.Windows.Media.Brushes.SlateGray;
            connection_Line.StrokeThickness = 2;
            connection_Line.FillRule = FillRule.EvenOdd;
   ->       var point = e.GetPosition();
            PointCollection myPointCollection = new PointCollection();
            myPointCollection.Add(point);
            connection_Line.Points = myPointCollection;
            parentCanvas.Children.Add(connection_Line);


        }
    }

1)第一个问题是在最后一个方法中包含的方法e.GetPosition()中添加什么作为参数,以便始终拥有鼠标所在的当前点。

2) 其次是在 parentcanvas 上添加事件处理程序来处理鼠标移动(在 output_MouseLeftButtonDown 中)是否合理,还是应该以不同的方式添加(而不是在 parentCanvas 上)?

3) 最后,如果整个功能都可以正常工作,或者有没有更好的方法通过鼠标移动来画线?

【问题讨论】:

  • 好吧,第一部分的答案可能是: var point = new Point(Mouse.GetPosition(parentCanvas).X, Mouse.GetPosition(parentCanvas).Y) 第二部分有什么提示吗?我应该在哪里分配 MouseMove 事件处理程序?

标签: c# wpf mouseevent


【解决方案1】:

我已经实现了一条与您的几乎相似的线。唯一的区别是我的行是在 xaml 视图中定义的,并且是从画布派生的特殊用户控件的一部分。 对于您的问题:

1.) getPosition 中的参数是与您要查找的位置相关的 InputElement。在您的 parentcanvas 上进行绘图时,请使用它。

2.) 如上所述,父画布是您的根元素,因此最好将 mouseHandler 附加到 parentCanvas MouseMove

3.) 我不会在每次鼠标移动时都创建一个新行。而是使用一条线(或在您的情况下为折线)作为私有成员,或者使用在 XAML 中定义的一条,并通过数据属性更改其几何。 例如

<Path x:Name="path" Stroke="Black" StrokeThickness="2" Data="{Binding PathGeometry}">

HTH

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多