C # Draw multiple lines
I am drawing multiple lines using this code, but I feel there is a better way to do it.
For example. using a multidimensional array? or a list?
private void drawLines()
{
int[] x1 = { 0, 0, 112, 222, 0, 333, 0, 1};
int[] x2 = { 334, 334, 112, 222, 334, 333, 334, 1 };
int[] y1 = { 100, 200, 300, 300, 1, 300, 300, 300 };
int[] y2 = { 100, 200, 0, 0, 1, 0, 300, 0 };
for (int i = 0; i < x1.Length; i++)
{
Line line = new Line();
Grid myGrid = gg;
line.Stroke = Brushes.Black;
line.X1 = x1[i];
line.X2 = x2[i];
line.Y1 = y1[i];
line.Y2 = y2[i];
line.StrokeThickness = 2;
myGrid.Children.Add(line);
}
}
+3
source to share
2 answers
I would make a Line class with the start and end points of the string in a struct Point and list that class instead of four arrays.
public class MyLine
{
public Point StartPoint {get; set;}
public Point EndPoint {get; set;}
public void DrawLine()
{
//Draw line code goes here
}
}
You now have a line class with a required field and a method to draw the line. The drawLines method, which may be in some other class, will create a list of the class MyLine and can draw this list of lines using the method of the Line classDrawLine
private void DrawLines()
{
List<MyLine> listMyLines = new List<MyLine>();
listMyLines.Add(new MyLine{StartPoint = new Point(0, 100), EndPoint = new Point(334, 100)});
for (int i = 0; i < listMyLines.Count; i++)
{
listMyLines[i].DrawLine();
}
}
+6
source to share
It could be better.
private void drawLInes()
{
drawLines(
new int[] { 0, 334, 100, 100 },
new int[] { 0, 334, 200, 200 },
new int[] { 112, 112, 300, 0 }
// ...
);
}
private void drawLines(params int[][] lines)
{
for (int i = 0; i < lines.Length; i++)
{
Line line = new Line();
Grid myGrid = gg;
line.Stroke = Brushes.Black;
line.X1 = lines[i][0];
line.X2 = lines[i][1];
line.Y1 = lines[i][2];
line.Y2 = lines[i][3];
line.StrokeThickness = 2;
myGrid.Children.Add(line);
}
}
+1
source to share