Just to know the best practice or code efficiency, I am having this piece of code :
Just to note: I am using .Net Compact Framework.
protected override void OnPaint(PaintEventArgs e)
{
if (BmpScreen == null)
{
BmpScreen = new Bitmap(ClientRectangle.Width, ClientRectangle.Height);
}
using (Graphics gBmpScreen = Graphics.FromImage(BmpScreen))
{
// some drawing using gBmpScreen
}
// finally
e.Graphics.DrawImage(BmpScreen, 0, 0);
}
In this piece of code in the Paint method I am creating a Graphics object every time,
my question is it better to do it like this or is it better to create the graphics object only once in the beginning ?
I’m not sure of the performance difference, but I’d recommend allocating and disposing of your back buffer Bitmap and Graphics objects in OnResize. I’ve found for most custom controls you can separate the actual work of updating the back buffer as close as possible to where the data changes occur, and simplify the the OnPaint to only blit the back buffer bitmap to the system’s Graphics. This worked well for a custom graph control I wrote, since the data did not change in response to user interaction. It was contained in a gesture scrolling control and greatly improved scrolling animation. But you could probably extend the pattern to handle more interactive controls by calling Update() in response to user interaction changes to force the OnPaint in the scope of your handler.