天天看點

将可視化對象呈現為圖像

使用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 儲存音樂或視訊縮略圖圖檔到本地