0

I'm currently trying to draw some lines in C# with the Graphics class.

My problem is, that sometimes (mostly on the repainting on resizing the form) some parts of the lines are missing.

This is how it looks like then:

drawn lines

This is my code where I draw the lines:

Graphics g = pnlGraph.CreateGraphics();
g.Clear(pnlGraph.BackColor);
Point p1 = new Point((mainNode.Left + (mainNode.Width / 2)), (mainNode.Top + (mainNode.Height / 2)));
Point p2 = new Point((pic.Left + (pic.Width / 2)), (pic.Top + (pic.Height / 2)));
g.DrawLine(new Pen(new SolidBrush(Color.Black), 2), p1, p2);

This code draws some lines from a mainNode in the middle of my panel to some nodes around it.

I'm calling the function to paint the lines on:

Load, Resize, Visible state changed

I also tried it in Paint of the form and the panel which didn't work.

Is there any way to fix it or another way of painting these lines?

Thanks for any answer!

virtualmarc
  • 533
  • 1
  • 4
  • 16
  • You might be interested in [my example](http://stackoverflow.com/a/15469477/643085) of a similar thing using current, relevant .Net Windows UI technologies. – Federico Berasategui Sep 08 '13 at 22:11
  • 3
    Sigh, again and again, and without the troll's "I don't know what's going on but throw anything you have away because I know this works" contribution, never ever use CreateGraphics(). That only works when you can afford to repaint 20+ frames per second. So that you don't care that you lose your previous paint output. Use the Paint event to draw. – Hans Passant Sep 08 '13 at 22:23
  • @HansPassant many people have said `"thank you, this is awesome!"` to my supposed "troll comments" because I made them save countless hours of trying to hack something useful out of an obsolete, completely useless technology, I will limit myself to show my examples to people and let them decide by themselves. – Federico Berasategui Sep 08 '13 at 22:30
  • @HansPassant Thanks for your answer. Can you please post this as an answer so I can mark it as answer? – virtualmarc Sep 09 '13 at 08:07

1 Answers1

1

Since the answer of @HansPassant has also made some problems we fixed the problem in another way:

We created an Image and filled it with an rectangle of the size of the panel. After that we draw the lines in the image and draw the image on the panel.

Graphics g = pnlGraph.CreateGraphics();
Image img = new Bitmap(pnlGraph.Width, pnlGraph.Height);
Graphics gi = Graphics.FromImage(img);
gi.DrawRectangle(new Pen(new SolidBrush(pnlGraph.BackColor)), new Rectangle(0, 0, pnlGraph.Width, pnlGraph.Height));
// For every line:
gi.DrawLine(new Pen(new SolidBrush(Color.Black), 2), p1, p2);
// At the end:
g.DrawImage(img, 0, 0, img.Width, img.Height);
virtualmarc
  • 533
  • 1
  • 4
  • 16