簡體   English   中英

如何使用C#通過鼠標移動畫一條線

[英]How to draw a line by the mouse move with C#

我想通過鼠標移動在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)其次是在父畫布上添加事件處理程序來處理鼠標移動(在output_MouseLeftButtonDown中)是否合理,還是應該以其他方式添加它(不在parentCanvas上)?

3)最后,如果希望整個功能正常運行,還是有更好的方法通過鼠標移動畫線?

我已經實現了一條與您幾乎相似的線條。 唯一的區別是,我的行是在xaml視圖中定義的,並且是從畫布派生的特殊用戶控件的一部分。 對您的問題:

1.)getPosition中的參數是InputElement,它與您要查找的位置有關。 在您的父畫布上進行繪制時,請使用此功能。

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

3.)每次鼠標移動時,我都不會創建新行。 寧可使用Line(或您的情況下的Polyline)作為私有成員,也可以使用XAML中定義的成員,然后通過Data Property更改其Geometry。 例如

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

高溫超導

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM