C# WinForms drawing a Bitmap on a PictureBox draws too many times

59 views Asked by At

I use a C# WinForms application with some PictureBoxes in there.
I drew some figures, at first (because of the size of the boxes) I didn't notice an error,
but after a few boxes I noticed, that my code ran fine,
but the images drawn were wrong.
It was as if the drawing methods were called many more times than in the debugger.

As you can see here:

[error drawing]

(https://i.stack.imgur.com/vE06K.png)

I ran my code multiple times,
had DoubleBuffering enabled/disabled for the Form, same behavior.
I used break points to see if I called the drawing more than once in my code,

but no, it was called once. I always use this in a method:

    Bitmap bmp = new Bitmap(Resources.<backgroundfile>, 342, 54);
    RectangleF rectfLage = new RectangleF(16, 14, 60, 22);
    Graphics graphicLageNr = Graphics.FromImage(bmp);
    graphicLageNr.SmoothingMode = SmoothingMode.AntiAlias;
    graphicLageNr.InterpolationMode = InterpolationMode.HighQualityBicubic;
    graphicLageNr.PixelOffsetMode = PixelOffsetMode.HighQuality;
    graphicLageNr.DrawString($"{lage}", new Font("Tahoma", 16), Brushes.Black, rectfLage);
    graphicLageNr.Flush();

After that, I set the Background of the PictureBox to NULL and then to the Bitmap.

    Controls[0].Controls[2].Controls["lagenr"].BackgroundImage = null
    Controls[0].Controls[2].Controls["lagenr"].BackgroundImage = bmp  

What could I have done wrong?

1

There are 1 answers

0
Steve On

Problem solved.
All I had to do was setting the right mode.
Picturebox.SizeMode has to be CenterImage.
Also assigning a Bitmap to a PictureBoxneeded to be like this: ((PictureBox)Controls[0].Controls[2].Controls[pb_name]).Image