目标
使用RenderTargetBitmap截图控件(或一组控件)。
资料来源:
<Grid Height="200" Width="500">
<!-- Here goes any content, in my case, a Label or a Shape-->
<Label VerticalAligment="Top" HorizontalAligment="Left" Content="Text">
</Grid>预期结果:

方法1
这个程序基本上使用UIElement作为RenderTargetBitmap的源。
public static ImageSource GetRender(this UIElement source)
{
double actualHeight = source.RenderSize.Height;
double actualWidth = source.RenderSize.Width;
var renderTarget = new RenderTargetBitmap((int)Math.Round(actualWidth),
(int)Math.Round(actualHeight), 96, 96, PixelFormats.Pbgra32);
renderTarget.Render(source);
return renderTarget;
}结果:

方法2:
我不直接将UIElement设置为RenderTargetBitmap的源,而是使用一个VisualBrush。
//Same RenderTargetBitmap...
DrawingVisual dv = new DrawingVisual();
using (DrawingContext ctx = dv.RenderOpen())
{
VisualBrush vb = new VisualBrush(target);
ctx.DrawRectangle(vb, null, new Rect(new Point(), bounds.Size));
}
rtb.Render(dv);结果:
这个选项忽略了Grid和Label在下面的位置和大小:

这里发生了什么事?
发布于 2015-08-26 14:02:28
修正方法2
我只需要得到Grid的后代的界限,并且只呈现所需的部分。
public static ImageSource GetRender(this UIElement source, double dpi)
{
Rect bounds = VisualTreeHelper.GetDescendantBounds(source);
var scale = dpi / 96.0;
var width = (bounds.Width + bounds.X)*scale;
var height = (bounds.Height + bounds.Y)*scale;
RenderTargetBitmap rtb =
new RenderTargetBitmap((int)Math.Round(width, MidpointRounding.AwayFromZero),
(int)Math.Round(height, MidpointRounding.AwayFromZero),
dpi, dpi, PixelFormats.Pbgra32);
DrawingVisual dv = new DrawingVisual();
using (DrawingContext ctx = dv.RenderOpen())
{
VisualBrush vb = new VisualBrush(source);
ctx.DrawRectangle(vb, null,
new Rect(new Point(bounds.X, bounds.Y), new Point(width, height)));
}
rtb.Render(dv);
return (ImageSource)rtb.GetAsFrozen();
}结果:
呈现的Label/Shape

与另一幅图片合并:

发布于 2018-08-06 03:30:05
这是因为RenderTargetBitmap基于其父对象的cordinate呈现可视对象。边缘本身、其父空间的填充或BorderThickness都将影响呈现的图像。要解决这个问题,您可以简单地添加一个假父容器:如果原始的可视逻辑树类似
<Grid>
<Canvas Margin="20" />
</Grid> 变到
<Grid>
<Border Margin="20">
<Canvas />
</Border>
</Grid> 对齐\页边距的设置也应移到父级。现在你会得到你想要的。
https://stackoverflow.com/questions/32210690
复制相似问题