问题
I'm creating an application for windows 8 metro, I need to render a framework control into an image and save it to hard disk but do not know how. Can I use SharpDX for this? How can I do? Thanks in advance for the help
回答1:
If you follow through this thread the limitations of Metro and the reasons why it won't work are explained. The essence of it is:
Sorry, but rendering Xaml to an element or capturing a screenshot of your own app did not make it into the release version. It is by design that an app cannot capturing a screenshot of another app.
A workaround mentioned is:
What I meant was - you can draw shapes, text and images using Direct2D. The same shapes that you would otherwise draw with XAML UI. I did not mean to imply that you can render XAML controls - just that you can use Direct2D as an alternative to achieve same results albeit with somewhat more effort.
回答2:
justin.m.chase's approach certainly works if you do not mind adding dependencies to SharpDX assemblies. The RenderTargetBitmap class might be a good fit for what you are trying to accomplish.
// Render XAML to bitmap
var bitmap = new RenderTargetBitmap();
await bitmap.RenderAsync(elementToRender);
// get the pixels
IBuffer pixelBuffer = await bitmap.GetPixelsAsync();
byte[] pixels = pixelBuffer.ToArray();
// write the pixels to a InMemoryRandomAccessStream
var stream = new InMemoryRandomAccessStream();
var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.BmpEncoderId, stream);
encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight, (uint)bitmap.PixelWidth, (uint)bitmap.PixelHeight, 96, 96, pixels);
await encoder.FlushAsync();
stream.Seek(0);
回答3:
I apologize that this is not possible. The WritableBitmap class' Render() method is current insufficient to accomplish what you are wanting. For the same reason a screenshot cannot be created at this time. But these are the things that are on the backlog! But, now you know.
回答4:
Because I think this is a more correct answer I would like to reiterate the comment that Zeeshan made in the original question.
There is a extension method for that in winrt xaml toolkit. http://winrtxamltoolkit.codeplex.com/.../WriteableBitmapRenderExtensions.cs
Install via nuget:
> Install-Package WinRTXamlToolkit.Composition
Add the using:
using WinRTXamlToolkit.Composition;
Render your xaml:
var bitmap = await element.Render();
来源:https://stackoverflow.com/questions/12640855/render-control-into-image-in-winrt-metro