Reputation: 543
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:
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!
Upvotes: 0
Views: 1156
Reputation: 543
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);
Upvotes: 1