在绘制wpf时动画一行

时间:2014-01-14 02:05:45

标签: c# wpf

XAML

<Canvas Name="canvas" MouseDown="canvas_MouseDown" MouseUp="canvas_MouseUp" Background="White" MouseMove="canvas_MouseMove" />

C#

Line AnimationLine;
Point P1;
private void canvas_MouseDown(object sender, MouseButtonEventArgs e)
{
    P1 = e.GetPosition(canvas);
    AnimationLine = new Line() { Stroke = new SolidColorBrush { Color = Colors.Blue },StrokeThickness = 3};
    AnimationLine.X1 = P1.X;
    AnimationLine.Y1 = P1.Y;
    canvas.Children.Add(AnimationLine);
}


private void canvas_MouseUp(object sender, MouseButtonEventArgs e)
{
    var P2 = e.GetPosition(canvas);
    canvas.Children.Remove(AnimationLine);
    //AnimationLine = new Line();
    canvas.Children.Add
      (new Line()
      {
          X1 = P1.X,
          Y1 = P1.Y,
          X2 = P2.X,
          Y2 = P2.Y,
          StrokeThickness = 3,
          Stroke = new SolidColorBrush { Color = Colors.Blue }
      });
}

private void canvas_MouseMove(object sender, MouseEventArgs e)
{
    if(e.LeftButton == MouseButtonState.Pressed)
    { 
       var P2 = e.GetPosition(canvas);
       AnimationLine.X2 = P2.X;
       AnimationLine.Y2 = P2.Y;
    }
}

我试图在鼠标按下时分配第一个点,在鼠标向上分配第二个点,当绘制线条时,这就是那个,但是在拖动时我想要显示动画线,动画线就像一个实时指南。

为了得到它我想画一条线就像在微软画中一样。

我刚刚写了上面的内容并且效果很好,但这真的是这样做的吗?任何可以帮助的内置功能?

1 个答案:

答案 0 :(得分:2)

您的代码可以简化如下所示。特别是,您应该为MouseLeftButtonDownMouseLeftButtonUp事件添加处理程序,而不是更常规的MouseDownMouseUp事件。另请注意,您通常会capture the mouse,并且使用鼠标处理程序的唯一目的是释放鼠标捕获。

XAML:

<Canvas Background="Transparent"
        MouseLeftButtonDown="Canvas_MouseLeftButtonDown"
        MouseLeftButtonUp="Canvas_MouseLeftButtonUp"
        MouseMove="Canvas_MouseMove"/>

代码背后:

private void Canvas_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    var canvas = (Canvas)sender;

    if (canvas.CaptureMouse())
    {
        var startPoint = e.GetPosition(canvas);
        var line = new Line
        {
            Stroke = Brushes.Blue,
            StrokeThickness = 3,
            X1 = startPoint.X,
            Y1 = startPoint.Y,
            X2 = startPoint.X,
            Y2 = startPoint.Y,
        };

        canvas.Children.Add(line);
    }
}

private void Canvas_MouseMove(object sender, MouseEventArgs e)
{
    var canvas = (Canvas)sender;

    if (canvas.IsMouseCaptured && e.LeftButton == MouseButtonState.Pressed)
    {
        var line = canvas.Children.OfType<Line>().LastOrDefault();

        if (line != null)
        {
            var endPoint = e.GetPosition(canvas);
            line.X2 = endPoint.X;
            line.Y2 = endPoint.Y;
        }
    }
}

private void Canvas_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
    ((Canvas)sender).ReleaseMouseCapture();
}