Draw a line in the middle of a line drawn by Graphics.DrawLine

I am printing a graph from my database like this:

   string sqli = "select e.startX, e.startY, e.endX, e.endY, e.length from edge e";
   queryCommand = new SqlCommand(sqli, cnn);
   queryCommandReader = queryCommand.ExecuteReader();
   dataTable = new DataTable();
   dataTable.Load(queryCommandReader);
   Pen blackPen = new Pen(Color.Black, 3);
   foreach (DataRow row in dataTable.Rows)
   {
        string startX= row["startX"].ToString();
        string startY= row["startY"].ToString()
        string endX= row["endX"].ToString();
        string endY= row["endY"].ToString()
        string length= row["length"].ToString()

        Point point1 = new Point(Int32.Parse(startX), Int32.Parse(startY));
        Point point2 = new Point(Int32.Parse(endX), Int32.Parse(endY));
        create.Paint += new PaintEventHandler((sender, e) =>
        {
            e.Graphics.DrawLine(blackPen, point1, point2);
            });
        }
        create.Refresh();
        cnn.Close();
    }

      

create

is mine panel

, I would also like to put string length

in the middle of the drawn line, give me a hint how should I do this?

+1


source to share


2 answers


As I noted, you add multiple red events to the panel. You should probably transfer your data or store your points at the form level so that the panel's paint event can access information within the region.

As for placing the text in the middle of the line, you can simply create a rectangle from the points of the line and center the text:



Point topLeft = new Point(Math.Min(point1.X, point2.X), Math.Min(point1.Y, point2.Y));
Point botRight = new Point(Math.Max(point1.X, point2.X), Math.Max(point1.Y, point2.Y));

TextRenderer.DrawText(e.Graphics, "X", this.Font,
               new Rectangle(topLeft,
                 new Size(botRight.X - topLeft.X, botRight.Y - topLeft.Y)),
               Color.Black, Color.White,
              TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter);

      

+3


source


You can try this:

        Point first = new Point(20, 40);
        Point second = new Point(100, 40);
        string str = "test";
        private void Form1_Paint(object sender, PaintEventArgs e)
        {
            Size s = TextRenderer.MeasureText(str,this.Font);
            double middle = (second.X + first.X) / 2;
            e.Graphics.DrawLine(Pens.Black, first,second);
            TextRenderer.DrawText(e.Graphics, str, this.Font, new Point((int)(middle - (s.Width / 2)), first.Y - s.Height), Color.Red);
        }

      



Of course you switch str with your string and two dots to yours.

0


source







All Articles