Drawing an image on the control panel gives artifacts when resizing

I'm currently trying to do what I thought would be a simple task:

Draw the image on the full Panel control area in Windows Forms. (Please ignore for now that I can use the BackgroundImage property)

The image for drawing is as follows:

enter image description here

those. yellow box with a 1-pixel blue border around.

To draw, I use the Paint event of the Panel control:

 private void panel1_Paint(object sender, PaintEventArgs e) { e.Graphics.DrawImage(Resources.MyImage, panel1.ClientRectangle); } 

This looks great when the form is initially displayed:

enter image description here

When resizing the form (and the docked panel, too), it either cuts the edges while reducing the size ...

enter image description here

... or he draws artifacts at magnification:

enter image description here

I am pretty sure that something pretty simple and straightforward is going on, but I really can't understand the reason.

Since I ignore ClipRectangle and always draw everything, I thought the image would scale all the time.

My questions:

  • What is the reason for artifacts? (I love to understand that!)
  • What do I need to do to get rid of artifacts? (besides calling Invalidate every time you resize)

Update, SOLUTION:

Thanks to Ryan's answer , I was able to find an acceptable solution. Basically, I got the class from Panel , made an override of OnPaintBackground and did not call the base method. Finally, I added the following code to the constructor of my derived panel:

 base.DoubleBuffered = true; SetStyle(ControlStyles.AllPaintingInWmPaint, true); SetStyle(ControlStyles.ResizeRedraw, true); SetStyle(ControlStyles.UserPaint, true); SetStyle(ControlStyles.OptimizedDoubleBuffer, true); UpdateStyles(); 
+7
source share
1 answer

The reason for the artifacts is that the entire surface does not redraw when resizing the form; only necessary parts. The most optimal solution is what you do not want to do, calling Invalidate every time you resize. However, if this is actually your situation, just use a PictureBox . If this is not the case, you can instead replace OnPaint in your form and use this.SetStyle(ControlStyles.ResizeRedraw, true) to do this automatically.

+4
source

All Articles