Keeping graphics unaltered when TabPage changes

2019-09-06 22:45发布

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条回答
贪生不怕死
2楼-- · 2019-09-06 23:25

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..

查看更多
登录 后发表回答