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>

期待される結果:

期待される

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

結果:

方法 1 結果

方法 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内側の位置とサイズを無視します:

ここに画像の説明を入力

ここで何が起こっているのですか?

4

2 に答える 2

3

修正方法 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:

レンダリング

別の画像と結合:

マージ済み

于 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 に答える