I'm trying to render bitmap created from drawing to screen but only render after minimize and maximize again.
I follow these steps: Using Bitmaps for Persistent Graphics in C#
But only can render bitmap in screen outside of Load_Form.
If I put the code:
using System.Drawing;
...
Graphics graphicsObj;
myBitmap = new Bitmap(this.ClientRectangle.Width,
this.ClientRectangle.Height,
Imaging.PixelFormat.Format24bppRgb);
graphicsObj = Graphics.FromImage(myBitmap);
Pen myPen = new Pen(Color.Plum, 3);
Rectangle rectangleObj = new Rectangle(10, 10, 200, 200);
graphicsObj.DrawEllipse(myPen, rectangleObj);
graphicsObj.Dispose();
In other place, for example a button, I need to minimize and maximize to see the image.
Edit:
bmp is a Bitmap global variable I create an instance in form event Load_Form1
bmp = new Bitmap(this.ClientRectangle.Width,
this.ClientRectangle.Height,
System.Drawing.Imaging.PixelFormat.Format24bppRgb);
Paint event of Form for redraw:
private void Form1_Paint(object sender, PaintEventArgs e)
{
Graphics graphicsObj = e.Graphics;
graphicsObj.DrawImage(myBitmap, 0, 0, myBitmap.Width, myBitmap.Height);
graphicsObj.Dispose();
}
But I need draw inmediately after create the drawing.
Not telling us about the bigger picture makes it hard to recommend the best course of action but let me simply assume two possible aims:
either you simply want something drawn onto the Form
or you want to display a bitmap into which you sucessively draw more and more things.
For the first all you need is to code the
Paint
event like this:If the data that control the drawing are dynamic you should store them at class level variables or lists of them and change them as needed so you can use them in the
Paint
event.For the latter aim there will be various times when you add to the Bitmap.
So you start by creating a, probably, class level
Bitmap
:And have one or more places where you draw into it like this:
Note how I
Invalidate
theForm
after changing theBitmap
, so thePaint
event is triggered.Also note that if these update happen really often it will be a good idea to keep the Graphics object alive between calls; either by making it a class variable like the Bitmap or by keeping it locally in the method that does all the updates and passing it out as a parameter to the drawing method..
In the form's
Paint
event all you need isAlso note that
32bppARGB
is the recommended default format. Is is used for anything you display in any case, so it is most efficient to use it to begin with..