问题
The following code throws a cryptic System.ArgumentException from the RenderAsync method "Value does not fall within the expected range." If on the other hand my Canvas is part of a visible XAML tree it works. Is it impossible to render some XAML that isn't displayed on screen?
Canvas c = new Canvas();
c.Width = 40;
c.Height = 40;
c.Background = new SolidColorBrush(Color.FromArgb(0xff, 0x80, 0xff, 0x80));
RenderTargetBitmap x = new RenderTargetBitmap();
await x.RenderAsync(c);
I almost thought this answer would work, but no luck, I guess it only applies to WPF: Create WPF element offscreen and render to bitmap
UPDATE:
So far my best idea is to put the Canvas I want to render to into the currently visible page but place it beneath what is normally the root UIElement that fills the screen so it isn't visible to the user:
<Grid>
<Canvas x:Name="HiddenCanvas"/>
<Grid x:Name="mainElement" Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
</Grid>
</Grid>
It isn't beautiful but it seems to work. Lets see if anyone can do better
回答1:
satur9nine's solution to put the rendered UI tree somewhere behind an opaque foreground seems to be the only supported solution. You could also fiddle with the opacity of the parent element to avoid having it showing up. Another option is to render it yourself with Direct2D or use something like the WinRTXamlToolkit.Composition.Render()
methods from WinRT XAML Toolkit.
回答2:
WinRTXamlToolkit.Composition
namespace has this extension that works. Just call this method:
await WriteableBitmapRenderExtensions.RenderToPngStream(element);
来源:https://stackoverflow.com/questions/18419810/in-winrt-c-sharp-how-do-i-save-an-offscreen-xaml-tree-using-rendertargetbitmap