客观的
使用 .截取一个控件(或一组控件)的屏幕截图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>
预期结果:
方法一
这一个基本上使用 .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;
}
结果:
方法二:
我不会直接将 设置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
内部的位置和大小:
这里发生了什么事?