Re: Drawing polygon

From: Fabian Schmied (REMOVETHISfabianDOTschmied_at_fhs-hagenbergDOTacDOTat)
Date: 05/14/04

Date: Fri, 14 May 2004 21:54:43 +0200

Michael Dengler schrieb:

> Why is the WinApi call so much faster?

Win32's Polyline is much faster than .NET's Graphics.DrawPolygon not
because of C, as Vas mentioned, but because it is GDI whereas
DrawPolygon is GDI+. At the moment, GDI+ does nearly all the drawing in
software, GDI is very optimized and does many things in hardware. In the
future, GDI+ should also use hw acceleration and graphics cards drivers
should be GDI+ optimized. But at the moment, GDI is faster.

> Do I have to get and release the
> DC every time in my loop or is it sufficient to do it one time.

While you hold a DC to the surface, it is locked and you can't do
anything with it. So you should release the DC as soon as you don't need
it any more.

> You told
> me to Dispose the Graphics object, why?

Because it implements IDisposable. Every object implementing IDisposable
should be disposed of when it isn't needed any more. This will prevent
resource leaks. Since you are Releasing the surface's DC (which was used
to create the Graphics object), you don't need the Graphics object any
more, so you should dispose it. C#'s using pattern can help here:

IntPtr dc = IntPtr.Zero;
try {
   using (Graphics g=Graphics.FromHdc(dc)) {
   } // g.Dispose is automatically called here
finally {
   if (dc != IntPtr.Zero) {

I also added a try/finally so that the surface DC is always released,
even if an exception occurs.