C# 仅渲染视觉对象的一部分

C# 仅渲染视觉对象的一部分,c#,wpf,C#,Wpf,我有一个大的DrawingVisual,它被添加到画布上,我想在单击鼠标时获得像素的颜色值。我尝试将整个Visaul渲染为RenderTargetBitmap,但出现“内存不足”异常。然后用我在这里找到的一个例子 我尝试只渲染部分视觉效果,但没有得到正确的像素值。目前我的代码如下所示 private void OnMouseDown(object sender, System.Windows.Input.MouseEventArgs e) { // Retreive the coordi

我有一个大的DrawingVisual,它被添加到画布上,我想在单击鼠标时获得像素的颜色值。我尝试将整个Visaul渲染为RenderTargetBitmap,但出现“内存不足”异常。然后用我在这里找到的一个例子

我尝试只渲染部分视觉效果,但没有得到正确的像素值。目前我的代码如下所示

private void OnMouseDown(object sender, System.Windows.Input.MouseEventArgs e)
{
    // Retreive the coordinates of the mouse button event.
    Point pt = e.GetPosition((UIElement)sender);

    VisualBrush vb = new VisualBrush(myDrawingVisual);
    vb.ViewboxUnits = BrushMappingMode.Absolute;

    // create rect from the position in the canvas - starting point of the DrawingVisual
    vb.Viewbox = new Rect(point.X - myDrawingVisual.ContentBounds.Left,point.Y - myDrawingVisual.ContentBounds.Top, 1, 1);
    vb.ViewportUnits = BrushMappingMode.Absolute;
    vb.Viewport = new Rect(point, new Size(1, 1));

    System.Windows.Shapes.Rectangle  r = new System.Windows.Shapes.Rectangle();
    r.Width = 1;
    r.Height = 1;
    r.Fill = vb;

    // Use RenderTargetBitmap to get the visual, in case the image has been transformed.
    var renderTargetBitmap = new RenderTargetBitmap(1,
                                                    1,
                                                    96, 96, PixelFormats.Default);
    renderTargetBitmap.Render(r);
    var pixels = new byte[4];
    renderTargetBitmap.CopyPixels(pixels, 4, 0);
}

您还没有布置矩形。有关详细信息,请参阅MSDN上的文章

添加以下行:

r.Measure(new Size(1, 1));
r.Arrange(new Rect(0, 0, 1, 1));

var renderTargetBitmap = ...
renderTargetBitmap.Render(r);