简体   繁体   中英

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

I am printing graph from my database as follows:

   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 my panel , I would like also to put string length in the middle of the drawn line, give me a hint how I should do that?

As I commented, you are adding multiple paint events to the panel. You should probably move your datatable or store your points at the form level so that the panel's paint event can access the information within it's scope.

As far as putting a text in the middle of the line, you can just create a rectangle from the line points 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);

You can try this one out:

        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);
        }

Ofcourse you switch str with your string and the 2 points by yours.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM