views:

29

answers:

1

Consider the following overriden OnPaint method for a .NET Control:

protected override void OnPaint(PaintEventArgs e)
{
   base.OnPaint(e);
   e.Graphics.RotateTransform(180);

   // lots of drawing code
}

Is it a problem that I do not restore the state of the e.Graphics object when I am finished?

In Java this is often done by making a copy of the passed Graphics object, thus the passed Graphics object is not altered and there is no need to restore it's state. Similar Java Question

I could achieve this in .NET by using the Save() / Restore() methods. So my questions are:

  • is it neccessary/best practice in .NET to restore the graphics state ?
  • how expensive are the Save() / Restore() methods?
+1  A: 

Well, whomever is going to implement the Paint event for the control is going to have a bit of a surprise. It could be valid if it makes sense that everything is always rotated, but that is for you to decide.

Graphics.Save + Restore takes about 4 microseconds on my laptop. Nothing to worry about given the typical expense of drawing.

Hans Passant
If Save and Restore are that quick then I think I will use them to restore the state at the end of my OnPaint.
GarethOwen
Actually, I didn't see that you called base.OnPaint() *before* drawing. Which isn't correct, you should allow a client event handler to draw on top of yours. Put base.OnPaint at the bottom and call Restore() before that.
Hans Passant
I'm not sure if it isn't correct. My base class is a Panel, and if that has a background color or image I want that to be drawn before I draw myself.
GarethOwen
That's what the OnPaintBackground() method does.
Hans Passant
I took the msdn example as template: http://msdn.microsoft.com/en-us/library/cksxshce.aspx
GarethOwen
Well, that code wants to draw a string even on top of whatever the user drew. Makes kinda sense, you wouldn't want to get parts of the string overdrawn. That isn't very common though, you usually let the user draw stuff on top. The user writing a bunch of custom drawing code and seeing it disappear is rarely a desirable outcome.
Hans Passant