Search code examples
c#.netuwppngsnapshot

How to capture a Node with transparent


For example, I have a UWP app, which has a node "Button" on it. Now, I want to make a snap for this Button. And, the output only includes this Button.

For JavaFX, we have the function "node.snapshot()", how about C# with UWP?


Solution

  • You could use RenderTargetBitmap class(which represents an image source that can be populated with the combined contents of a XAML visual tree) to do the job.

    For example:

    //Page.xaml 
    <StackPanel>
        <Button x:Name="capturedButton" Content="capture me" Margin="10"/>
        <Button x:Name="button" Content="click me" Margin="10" Click="button_Click"/>
        <Image x:Name="image" Margin="10" Width="200" Height="200" Stretch="None"/>
    </StackPanel>
    
    //Page.xaml.cs
    private async void button_Click(object sender, RoutedEventArgs e)
    {
        RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap();
        await renderTargetBitmap.RenderAsync(capturedButton);
        image.Source = renderTargetBitmap;
    }