If I have a DrawingVisual in WPF with Opacity=0, is that enough for it not to be drawn? We have hundreds of DrawingVisuals on a Canvas, and are currently setting Opacity=0 o
The best way to check would be to instead set the Visibility to Visibility.Colapsed, and see if there's any drawing performance differences.
Visibility.Colapsed ensures that the element is not visible but also that it will not participate in the Arrange, Measure and Render passes of the UI, while an element with Opacity=0 might participate in all passes.
I solved a very similar problem by using a DrawingGroup and adding or removing Drawing objects from the DrawingGroup
as they either needed to be displayed or hidden. The key is to organize your Drawing
objects in such a way that they are easy to manage and to understand how to add and remove them from the DrawingGroup
.
Remember that you want to add and remove the Drawing
objects from the DrawingCollection exposed by the DrawingGroup.Children property. So use DrawingGroup.Children.Add() or the other DrawingCollection
methods: Insert, Remove, RemoveAt, Clear. You will need to keep an external list of the Drawing
objects you add/remove to the DrawingGroup
to do this successfully.
I used this technique to great effect by drawing an Image (bitmap) into the first child in my instance of DrawingGroup
and then adding and removing Drawing
objects to this instance of DrawingGroup
in order to layer polygons, paths, text, etc on top of the drawing.
I "draw" or "erase" on the image by adding or removing Drawing
objects to the instance of the DrawingGroup
. The DrawingGroup
is treated as a single Drawing
and so any scaling, panning, or other manipulations will affect all Drawing
objects within the DrawingGroup
.
The most efficient seems to be setting the opacity in my tests. Another simple approach is to redraw the visuals that are affected.
using (DrawingContext dc = RenderOpen()) {} //Hide this visual
And then redraw when they become visible again.
Rendering a blank drawingcontext seems to be very quick. But if you have complicated visuals it could take time to rerender them when they become visible.
Why not simply remove the visual from the visual children list? When it needs to be visible you add it back.