如何绘制运动轴表

时间:2019-07-17 17:35:34

标签: c# wpf

我正在尝试从WPF的代码后面绘制一个轴表(x-y);我想给它拖放选项,它可以看到更多的轴表。 我创建了静态轴,但不知道如何创建动态轴? 有人可以帮我这个东西吗? 谢谢。

            for (int i = 10; i < 400; i+=10)
        {
            Line a = new Line();
            a.X1 = 0;
            a.Y1 = i;
            a.X2 = canGraph.Width;
            a.Y2 = a.Y1;
            a.Stroke = System.Windows.Media.Brushes.Black;
            a.StrokeThickness = 0.5;
            canGraph.Children.Add(a);

            Line b = new Line();
            b.X1 = i;
            b.Y1 = 0;
            b.X2 = i;
            b.Y2 = canGraph.Height;
            b.Stroke = System.Windows.Media.Brushes.Black;
            b.StrokeThickness = 0.5;
            canGraph.Children.Add(b);
            if (i % 50 == 0)
            {
                a.StrokeThickness = 1;
                b.StrokeThickness = 1;
            }

            if (i == 200)
            {
                a.StrokeThickness = 2;
                b.StrokeThickness = 2;
            }



        }

2 个答案:

答案 0 :(得分:1)

这应该使您入门。将事件处理程序添加到主轴和canGraph-

    ...
    if (i == 200)
    {
       a.StrokeThickness = 2;
       b.StrokeThickness = 2;

       a.MouseLeftButtonDown += A_MouseLeftButtonDown;
    }
}
canGraph.MouseLeftButtonUp += CanGraph_MouseLeftButtonUp;
canGraph.MouseMove += CanGraph_MouseMove;

添加以下方法-

    Line _selectedAxis = null;

    private void CanGraph_MouseMove(object sender, MouseEventArgs e)
    {
        if (_selectedAxis != null)
        {
            var line = _selectedAxis;
            var pos = e.GetPosition(line);
            textBlock.Text = $"({pos.X}, {pos.Y})";
            line.Y1 = pos.Y;
            line.Y2 = pos.Y;
        }
    }

    private void CanGraph_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
    {
        _selectedAxis = null;
    }

    private void A_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        var line = sender as Line;
        _selectedAxis = line;
    }

现在按住主水平轴并将其拖动。

您也可以对垂直轴进行同样的操作。

用于缩放

使用canGraph.RenderTransform初始化ScaleTransform并订阅MouseWheel事件。注意RenderTransformOrigin设置为(0.5,0.5)以从中心而不是左上方缩放(默认)-

canGraph.RenderTransformOrigin = new Point(0.5, 0.5);
canGraph.RenderTransform = new ScaleTransform();
canGraph.MouseWheel += CanGraph_MouseWheel;

函数-

private void CanGraph_MouseWheel(object sender, MouseWheelEventArgs e)
{
    var transform = canGraph.RenderTransform as ScaleTransform;
    var factor = transform.ScaleX;
    factor += (e.Delta > 0 ? 1 : (factor == 1 ? 0 : -1));
    transform.ScaleX = factor;
    transform.ScaleY = factor;
}

答案 1 :(得分:0)

我猜您已经添加了Line类型的对象来绘制轴,然后将其提供给窗口内容。
然后只需添加事件,例如MouseLeftButtonDown事件或MouseMove事件。添加适当的方法。
MouseMove事件中更改对象位置,例如: (对于某行)

private void MouseMoveMethod(object sender, MouseEventArgs e)
        {
            var obj = sender as Line;

            obj.X1 = e.GetPosition(this).X; //Line start x coordinate
            obj.Y1 = e.GetPosition(this).Y; //Line start y coordinate
            ...
        }