使用RenderTargetBitmap类,可以将用户界面上的某个可视化元素以及它的子元素呈现到内存图像中。只需简单调用RenderAsync方法就可以完成,在调用方法时传入的可视化对象类型要求为UIElement,也就是说,只要是从UIElement类派生的类型实例都可以在RenderTargetBitmap位图中呈现。
接下来将通过示例来演示RenderTargetBitmap类的用法。
示例的XAML代码如下:
<ScrollViewer>
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition Height="auto"/>
<RowDefinition Height="auto"/>
</Grid.RowDefinitions>
<Border x:Name="bdroot" Margin="20" BorderBrush="White" BorderThickness="5" CornerRadius="25"
Height="300" Width="300">
<StackPanel VerticalAlignment="Center">
<TextBlock Text="文本内容" HorizontalAlignment="Center" FontSize="28"/>
<Ellipse Width="200" Height="150" Fill="Orange"/>
<StackPanel Orientation="Horizontal">
<CheckBox Content="item 1"/>
<CheckBox Content="item 2" IsChecked="True"/>
</StackPanel>
<Polyline Stretch="Uniform" Points="0,15 30,0 65,25 120,5 220,20 320,0" Stroke="Pink" StrokeThickness="9"/>
</StackPanel>
</Border>
<Button Grid.Row="1" Content="生成图像" Tapped="Button_Tapped"/>
<Image x:Name="img" Grid.Row="2" Margin="15" Height="300" Width="300"/>
</Grid>
</ScrollViewer>
当Button被单击后,将Border元素以及子元素呈现到位图中,然后使用Image控件来显示生成的位图。Button的Click事件处理代码如下:
private async void Button_Tapped(object sender, TappedRoutedEventArgs e)
{
RenderTargetBitmap renderBmp = new RenderTargetBitmap();
await renderBmp.RenderAsync(bdroot);
img.Source = renderBmp;
}
从上面代码中可以看到,只要调用RenderTargetBitmap实例的RenderAsync方法即可将指定的UI元素生成到内存位图中。
运行应用程序,然后单击"生成图像"按钮,就会在页面下方的Image控件中显示刚生成的图像,如下所示:
如若想将位图保存到本地,参见博客: UWP 保存音乐或视频缩略图图片到本地