I need to draw gridlines on the background of a canvas that will have other controls placed on it.
I tried creating a StreamGeometry, using that to draw lines, and getting that assigned to a DrawingBrush. However I find that if the StreamGeometry has too many lines, the program becomes sluggish after the DrawingBrush is assigned to the Canvas.
Is there anyway of 'pre-rendering' grid lines and having that assigned to a Canvas?
I tried Freeze()ing the brush and geometry but that didn't seem to work. What other options do I have?
Here's my code:
public void RenderGrid()
{
this.UpdateGrid();
Pen grid_pen = new Pen(Brushes.Blue, 0.1);
StreamGeometry sg = new StreamGeometry();
DrawingBrush b = new DrawingBrush();
GeometryDrawing gd = new GeometryDrawing();
gd.Geometry = sg;
gd.Pen = grid_pen;
b.Drawing = gd;
StreamGeometryContext ctx = sg.Open();
foreach (double d in this.VerticalGrids)
{
ctx.BeginFigure(new Point(d, 0), true, false);
ctx.LineTo(new Point(d, this.RenderSize.Height), true,false);
}
foreach (double d in this.HorizontalGrids)
{
ctx.BeginFigure(new Point(0, d), true, false);
ctx.LineTo(new Point(this.RenderSize.Width, d),true, false);
}
ctx.Close();
sg.Freeze();
gd.Freeze();
b.Freeze();
this.Background = b;
}
My advice would be to keep the primitive count down. You're making WPF spend CPU cycles and bandwidth creating and sending that massive grid to the render thread and GPU.
DrawingBrush is a TileBrush.
Draw a single unit of the grid onto the DrawingImage and use the TileMode, Viewbox and Viewport properties to tile the grid.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With