目的

使用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>


预期结果:

c# - RenderTargetBitmap位置问题-LMLPHP

方法一

这基本上是使用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;
}


结果:

c# - RenderTargetBitmap位置问题-LMLPHP

方法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);


结果:

这个忽略了GridLabel在里面的位置和大小:

c# - RenderTargetBitmap位置问题-LMLPHP

这里发生了什么事?

最佳答案

修改方法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位置问题-LMLPHP

与另一张图片合并:

c# - RenderTargetBitmap位置问题-LMLPHP

关于c# - RenderTargetBitmap位置问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32210690/

10-10 10:41