Fast 2D graphics in WPF

前端 未结 5 1199
庸人自扰
庸人自扰 2020-12-12 13:42

I need to draw a large amount of 2D elements in WPF, such as lines and polygons. Their position also needs to be updated constantly.

I have looked at many of the an

5条回答
  •  难免孤独
    2020-12-12 14:39

    The fastest WPF drawing method I have found is to:

    1. create a DrawingGroup "backingStore".
    2. during OnRender(), draw my drawing group to the drawing context
    3. anytime I want, backingStore.Open() and draw new graphics objects into it

    The surprising thing about this for me, coming from Windows.Forms.. is that I can update my DrawingGroup after I've added it to the DrawingContext during OnRender(). This is updating the existing retained drawing commands in the WPF drawing tree and triggering an efficient repaint.

    In a simple app I've coded in both Windows.Forms and WPF (SoundLevelMonitor), this method empirically feels pretty similar in performance to immediate OnPaint() GDI drawing.

    I think WPF did a dis-service by calling the method OnRender(), it might be better termed AccumulateDrawingObjects()

    This basically looks like:

    DrawingGroup backingStore = new DrawingGroup();
    
    protected override void OnRender(DrawingContext drawingContext) {      
        base.OnRender(drawingContext);            
    
        Render(); // put content into our backingStore
        drawingContext.DrawDrawing(backingStore);
    }
    
    // I can call this anytime, and it'll update my visual drawing
    // without ever triggering layout or OnRender()
    private void Render() {            
        var drawingContext = backingStore.Open();
        Render(drawingContext);
        drawingContext.Close();            
    }
    

    I've also tried using RenderTargetBitmap and WriteableBitmap, both to an Image.Source, and written directly to a DrawingContext. The above method is faster.

提交回复
热议问题