Draw a line in the middle of a line

I need to draw text (number) in the middle of a line drawn with Graphics.DrawLine

like this:

1 and 2 are buttons. I achieved this using the answer here . The problem with this solution is that it ignores the fact that the beginning of the line may be vertically below the end point (in this case the text overlaps with the line and at a certain point disappears as here: .

I know how to solve the main problem here when the starting point is vertically lower, but how can I make it so that it doesn't intersect with the line like in the following image? enter image description here

+3


source to share


1 answer


Updated Based on comments.

I believe you are looking for something like below (note that I used test data, it takes a little work. It takes 2 points, creates the median, measures your line, offsets the median and draws the line.



 private void Form1_Paint(object sender, PaintEventArgs e)
 {
     var pt1 = new Point(25, 25);
    var pt2 = new Point(100, 10);
    var ptMed = new Point((pt1.X + pt2.X) / 2, (pt1.Y + pt2.Y) / 2);
    var g = e.Graphics;
    var lbl = "1";
    var offset = g.MeasureString(lbl, this.Font);
    ptMed.Y -= (int)offset.Height;
    ptMed.X -= (int)offset.Width;
    var p = new Pen(Brushes.White);
    g.DrawLine(p, pt1, pt2);
    g.DrawString(lbl, this.Font, Brushes.White, ptMed);
 }

      

enter image description here

+1


source







All Articles