Getting a DrawingContext for a wpf WriteableBitmap

前端 未结 5 452
逝去的感伤
逝去的感伤 2020-11-30 05:15

Is there a way to get a DrawingContext (or something similar) for a WriteableBitmap? I.e. something to allow you to call simple DrawLine

5条回答
  •  春和景丽
    2020-11-30 05:25

    A different way to solve this problem is to use a RenderTargetBitmap as a backing store, just like in the WriteableBitmap example. Then you can create and issue WPF drawing commands to it whenever you want. For example:

    // create the backing store in a constructor
    var backingStore = 
          new RenderTargetBitmap(200,200,97,97,PixelFormats.Pbgra32);
    myImage.Source = backingStore;
    
    // whenever you want to update the bitmap, do:
    var drawingVisual = new DrawingVisual();
    var drawingContext = drawingVisual.RenderOpen();
    {
        // your drawing commands go here
        drawingContext.DrawRectangle(
                Brushes.Red, new Pen(),
                new Rect(this.RenderSize));
    }
    Render(drawingContext);
    drawingContext.Close();
    backingStore.Render(drawingVisual);
    

    If you want to redraw this RenderTargetBitmap every frame, you can catch the CompositionTarget.Rendering event, like this:

    CompositionTarget.Rendering += MyRenderingHandler;
    

提交回复
热议问题