0
votes

I have a large DrawingVisual that is added to a Canvas and I want to get the color value of a pixel when I click the mouse. I tried rendering the entire Visaul to a RenderTargetBitmap but got an "Out of memory" exception. then using an example I found here How to render (bitmap) only part of a Visual?

I tried rendering only part of the Visual but I dont get the correct pixel value. currently my code looks like this

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);
}
1

1 Answers

0
votes

You haven't laid out the Rectangle. For details refer to the Layout article on MSDN.

Add the following lines:

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

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