Search code examples
c#.netwpf2dpen

Why does use of pens with dash patterns cause huge (!) performance degredation in WPF custom 2D drawing?


Hope anyone can shed light on this so I can use pens with dash patterns?

I am writing a scrollable chart (a Panel inside ScrollViewer that implements IScrollInfo) in WPF using DrawingVisual's DataContext.DrawX. I have several thousand DrawingVisuals that get scrolled by using TranslateTransform on the Panel that hosts them. I implemented a grid by placing a Panel on top of it and drawing simple horizontal lines from one edge to the other using DataContext.DrawLine(pen, new Point(0, y), new Point(widthOfPanel, y)); //(note: these lines are always static, they never move).

The scroll performance is absolutely insane (i.e. DrawingVisual's are drawn instantly and scrolling is instant). But if I use a Pen that uses dash patterns (see below for example) to draw the grid lines, then scrolling is very jerky and the performance seems to have been decreased by a factor of 100 (an estimate). Can anyone explain why that happens and how I can workaround this?

Example of Pen with dash pattern:

<Pen x:Key="PenUsingDashPatterns" Brush="Black" Thickness="1">
   <Pen.DashStyle >
      <DashStyle Dashes="3, 3" />
   </Pen.DashStyle>
</Pen>

Solution

  • Are the pens getting frozen? Freezing drawing objects helps performance a lot.

    You could set up a Loaded handler and debug to see if your pens are frozen. If not, Call the Pen.Freeze() button manually on them.

    Note that freeze also makes the pens read-only... you will be unable to modify them after you freeze them.