I am working on a project in which I have to draw different nodes(junctions) and then show connection between them. Simply, I used ellipse class to draw the nodes with their coordinates as (x, y) on Canvas inside ViewBox
.Then, all i did was read the link's starting and ending coordinate and stored them in a List and by reading the List, I added them to the canvas.
I have the following code to draw the line on canvas
which reads the start point and endpoint:
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);
}
And the ds object calls the drawLine function.
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;
}
Now, i need these drawn lines to be directed i.e. having arrows in the middle which shows the path from (x1, y1) to (x2, y2) i.e. point from starting point to ending point. Can somebody give me a direction?
Ok I have now solved my own problem. I followed the PETZOLD BOOK BLOG
and downloaded the file and used three classes that I needed.
Then i changed my code to:
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);
}
Then, I added 2 lines of code to the function PathFigure in ArrowLineBase.cs as:
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;
}
The added code places the position of the arrow to be at the midpoint of the drawn line. Just using the midpoint formula. You can standardize the code by adding a enum in ArrowEnds.cs and add logic ArrowLineBase.cs.