我有一个大的DrawingVisual添加到Canvas中,我想在单击鼠标时获取像素的颜色值。我尝试将整个Visaul渲染到RenderTargetBitmap但得到了“Out of memory”异常。然后使用我在How to render (bitmap) only part of a Visual?
找到的示例我尝试只渲染部分Visual,但我没有得到正确的像素值。目前我的代码看起来像这样
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);
}
答案 0 :(得分:0)
你还没有布置矩形。有关详细信息,请参阅MSDN上的Layout文章。
添加以下行:
r.Measure(new Size(1, 1));
r.Arrange(new Rect(0, 0, 1, 1));
var renderTargetBitmap = ...
renderTargetBitmap.Render(r);