Friday, December 05, 2008

Saving and restoring GDI+ state

When you create complex drawing code, you probably will split this over multiple methods and pass the Graphics-object between these methods. But because the Graphics-object contains state, all changes that you apply in a method will be propagated to the other methods as well. Often this is not what you want.

The common way to work around this is to reset all the changes that you made at the end of the method:

   1: void PaintBackGround(Graphics g)
   2: {
   3:     SmoothingMode oldSmoothingMode = g.SmoothingMode;
   4:     try
   5:     {
   6:         g.SmoothingMode = SmoothingMode.AntiAlias;
   7:         ...
   8:     }
   9:     finally
  10:     {
  11:         g.SmoothingMode = oldSmoothingMode;
  12:     }
  13: }

But if your code changes a lot of properties this will become cumbersome. In these cases it is simpler to save and restore the entire Graphics-state like this:

   1: void PaintBackGround(Graphics g)
   2: {
   3:     GraphicsState oldState = g.Save();
   4:     try
   5:     {
   6:         g.SmoothingMode = SmoothingMode.AntiAlias;
   7:         ...
   8:     }
   9:     finally
  10:     {
  11:         g.Restore(oldState);
  12:     }
  13: }

No comments: