R – GDI+ DashStyle throws OutOfMemoryException in .NET

gdi+netout-of-memorypenwinforms

I'm using DashStyle.Dash while rendering my hierarchy of objects. My application uses Graphics.Transform extensively and I find that at some scale values (including a scale of 100%) and some angles of rotation, Graphics.DrawLine throws OutOfMemoryException when using a pen with DashStyle.Dash. Using Google I found that this is a well-known problem. Microsoft tells us that this is not a blocking issue. So far, I have not found a workaround for this problem.

What are my options?

Best Answer

I just encountered the same issue. Upon further investigation I discovered the following.

  1. The line length was exactly the custom dash pattern length. Changing the line length +/- 1 pixel avoided the error.
  2. I was using LineCapRound and DashCapRound, switching to LineCapSquare and DashCapFlat avoided the error
  3. The error came from trying flatten the path (presumably from the rounded ends)
  4. The pen width was zero.

My final solution was to not draw zero width lines!