问题
I have a form that displays a set of graphics using a Paint
event on a Panel
that is docked inside a particular TabPage
of a TabControl
.
The problem is the following:
When the user switches to a different TabPage
and then decides to go back to the TabPage
where the graphics were originally displayed, those graphics are invalidated by default so the Panel
appears blank.
I would like those graphics to stay unaltered and totally independent from the user's action when switching between different TabPages.
One Requirement:
Since the graphics are complex and take some time to be drawn by the computer, I don't want to repaint the graphics each time by calling the Paint
event repeatedly. Instead, I only need to avoid the default invalidation of the graphics.
I have read this other question which may be helpful to solve my problem but it goes beyond my knowledge.
回答1:
If you want to cache your graphics you can draw everything into a bitmap and set it to the panel's background image.
Here is some example code, using a Control
. Simply pass in your Panel
:
void drawInto(Control ctl)
{
Bitmap bmp = new Bitmap(ctl.ClientSize.Width, ctl.ClientSize.Height);
using ( Graphics G = Graphics.FromImage(bmp))
{
// all your drawing code goes here..!
G.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
G.DrawEllipse(Pens.DimGray, ctl.ClientRectangle);
// ..
// ..
}
ctl.BackgroundImage = bmp;
}
Just make sure to call the drawing function whenever necessary, as this is now your responsibility. The Resize
event of the Panel
is a good example of where you need to call it!
And changes in the data coming from the user are the obvious other reason to call it..
来源:https://stackoverflow.com/questions/31104272/keeping-graphics-unaltered-when-tabpage-changes