3

客观的

使用 .截取一个控件(或一组控件)的屏幕截图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;
}

结果:

方法 1 结果

方法二:

我不会直接将 设置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内部的位置和大小:

在此处输入图像描述

这里发生了什么事?

4

2 回答 2

3

修改方法二

我只需要获取后代的边界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

渲染

与另一张图片合并:

合并

于 2015-08-26T14:02:28.393 回答
-1

这是因为 RenderTargetBitmap 根据其父对象的坐标来渲染视觉对象。自身的边距、父级的 Padding 或 BorderThickness 都会影响渲染图像。为了解决这个问题,你可以简单地添加一个假的父容器:如果原来的可视化逻辑树是这样的

<Grid>
    <Canvas Margin="20" />
</Grid> 

变成

<Grid>
    <Border Margin="20">
        <Canvas />
    </Border>
</Grid> 

Alignment\Margin 的设置也应该移到父级中。现在你会得到你想要的。

于 2018-08-06T03:30:05.940 回答