行中间的箭头c#

时间:2016-01-08 05:54:23

标签: c# wpf graphics2d

我正在开发一个项目,我必须在其中绘制不同的节点(交汇点),然后显示它们之间的连接。简单地说,我使用椭圆类ViewBox内的Canvas上绘制坐标为(x,y)的节点。然后,我所做的就是读取链接的起始和结束坐标并存储他们在列表中,通过阅读列表,我将它们添加到画布中 我有以下代码在canvas上绘制线条,该线条读取起点和终点:

foreach(LineProperty lnp in lstLnPro){
            Line ln = new Line();
            ln = ds.drawLine(lnp.x1, lnp.y1, lnp.x2, lnp.y2);
            ln.MouseEnter += ln_MouseEnter;
            ln.MouseLeave += ln_MouseLeave;


            canvasName.Children.Add(ln);
        }

ds对象调用drawLine函数。

public Line drawLine(double x1, double y1, double x2, double y2) {
        Line ln = new Line();
        ln.X1 = x1;
        ln.Y1 = y1;
        ln.X2 = x2;
        ln.Y2 = y2;
        ln.StrokeThickness = 1;
        ln.Visibility = System.Windows.Visibility.Visible;
        ln.Stroke = System.Windows.Media.Brushes.Green;
        return ln;
    }

现在,我需要引导这些绘制的线,即在中间具有箭头,其显示从(x1,y1)到(x2,y2)的路径,即从起点到终点的点。有人能指点我吗?

1 个答案:

答案 0 :(得分:2)

好的我现在已经解决了我自己的问题。我跟着PETZOLD BOOK BLOG

并下载了该文件并使用了我需要的三个类。

  • ArrowLine.cs
  • ArrowEnds.cs
  • ArrowLineBase.cs

然后我将代码更改为:

        foreach(LineProperty lnp in lstLnPro){
            ArrowLine line= new ArrowLine();
            line.Stroke = Brushes.Green;
            line.StrokeThickness = 1;
            line.X1 = lnp.x1;
            line.Y1 = lnp.y1;
            line.X2 = lnp.x2;
            line.Y2 = lnp.y2;
            line.ArrowLength = 3;

            canvasName.Children.Add(line);

}

然后,我在ArrowLineBase.cs中的函数PathFigure中添加了两行代码:

PathFigure CalculateArrow(PathFigure pathfig, Point pt1, Point pt2)
    {
        Matrix matx = new Matrix();



        Vector vect = pt1 - pt2;
        vect.Normalize();
        vect *= ArrowLength;


        PolyLineSegment polyseg = pathfig.Segments[0] as PolyLineSegment;
        polyseg.Points.Clear();
        matx.Rotate(ArrowAngle / 2);

        //added code starts
       //places the position of the arrow on the midpoint
        pt2.X = (pt2.X + pt1.X) / 2;
        pt2.Y = (pt2.Y + pt1.Y) / 2;
        //added code ends

        pathfig.StartPoint = pt2 + vect * matx;
        polyseg.Points.Add(pt2);

        matx.Rotate(-ArrowAngle);
        polyseg.Points.Add(pt2 + vect * matx);
        pathfig.IsClosed = IsArrowClosed;

        return pathfig;
    }

添加的代码将箭头的位置放在绘制线的中点。只需使用中点公式。您可以通过在 ArrowEnds.cs 中添加枚举来标准化代码,并添加逻辑 ArrowLineBase.cs