如何使用C#将在后台代码中创建的UIElement转换为流?

时间:2019-04-09 05:01:24

标签: c# uwp

我没有使用Xaml在后台代码中动态创建了UIelements,我需要将其转换为流。我尝试了RenderTargetBitmap。但这是行不通的,还有其他可行的方法吗?

     private async void ConverteToImage(UIElement element, int pageIndex)         
       {

        RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap();

        await renderTargetBitmap.RenderAsync(element); // Render canvas.
        var pixelBuffer = await renderTargetBitmap.GetPixelsAsync();
        var logicalDpi = DisplayInformation.GetForCurrentView().LogicalDpi;
        using (var stream = new InMemoryRandomAccessStream())
        {
            var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream);
            encoder.SetPixelData(
            BitmapPixelFormat.Bgra8,
            BitmapAlphaMode.Ignore,
            (uint)renderTargetBitmap.PixelWidth,
            (uint)renderTargetBitmap.PixelHeight,
            logicalDpi,
            logicalDpi,
            pixelBuffer.ToArray());
            await encoder.FlushAsync();
            SaveAsCustomStamp(stream.AsStream(), pageIndex, loadedDocument);
        }
    }

0 个答案:

没有答案