目的
使用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;
}
结果:
方法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
在里面的位置和大小:这里发生了什么事?
最佳答案
修改方法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
:与另一张图片合并:
关于c# - RenderTargetBitmap位置问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32210690/