在Graphics.DrawLine绘制的线条中间绘制字符串

时间:2014-05-30 22:13:48

标签: c#

我正在从我的数据库打印图表,如下所示:

   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是我的panel,我还想将string length放在绘制线的中间,给我一个提示我应该怎么做?

2 个答案:

答案 0 :(得分:3)

正如我评论的那样,您正在向面板添加多个绘制事件。您应该移动数据表或将您的积分存储在表单级别,以便面板的绘制事件可以访问其范围内的信息。

只要将文本放在行的中间,您就可以从行点创建一个矩形并将文本居中:

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

答案 1 :(得分:0)

你可以试试这个:

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

当然,你用你的字符串切换str,你的2点。