Performance of FillRectangle() and Clear()

I have written a WinForms custom control that draws (and allows editing of) a graphical based document on a page (for example, look how Microsoft Word draws a blank page with the dropshadow etc.). Pseudocode for the basic repainting method is along the lines of,

protected void PaintDocument(Graphics g)
{
Clear background to desired backcolor
(via Graphics.Clear())
Fill a black rectangle for the page's drop-shadow
(via Graphics.FillRectangle())
Fill a white rectangle for the page itself
(via Graphics.FillRectangle())
Perform some custom drawing code
}

The custom drawing code draws the actual contents of the document, and does quite a lot of calculations, painting polygons, and some pretty complex clipping regions.

I was a little concerned about performance so have just run a profiler over my code. Much to my surprise, only approximately 25% of my painting time is spent in my custom code, whereas the Clear() and FillRectangle() calls take up about 25% each. [Interestingly, if I turn off double buffering (with DoubleBuffered=false) then Clear() drops to only 0.05%, but FillRectangle() still takes most of the time.]

Why are Clear() and FillRectangle() so slow?!? Is there anything I can do to improve performance with these calls?

-
Andrew Wilkinson

[1460 byte] By [AndyWilkinson] at [2007-12-17]
# 1
You could try checking the incoming clip rectangle and only bother with drawing the area that is actually invalid. It might be that you are always drawing the entire client area when only a small portion is actually invalid.

Are you using solid colors or more complex gradient or texture brushes for the drawing? Drawing a solid block of color using Graphics.FillRect should be very fast.

Phil Wright
www.ComponentFactory.com
Free VS2005 User Interface Controls

PhilipWright at 2007-10-6 > top of Msdn Tech,Windows Forms,Windows Forms General...
# 2

Most of the redrawing is initiated by a user edit followed by a call to Invalidate(), so I'm drawing the whole client area every time. But I'm using a SolidBrush for the fill, so as you say, even filling the whole client shouldn't be a real problem performance-wise.

I'll see if I can track down the problem,
Andrew Wilkinson

AndyWilkinson at 2007-10-6 > top of Msdn Tech,Windows Forms,Windows Forms General...