Universal Windows InkCanvas strokes disappear on RenderTargetBitmap.RenderAsync

后端 未结 2 991
夕颜
夕颜 2021-01-14 07:01

I try to render the strokes of a InkCanvas to a RenderTargetBitmap in a windows 10 universal App. Here is my xaml code:



        
2条回答
  •  攒了一身酷
    2021-01-14 07:39

    You can use Win2D to render the Ink Strokes.

    1. Add Win2D.uwp to the project from NuGet
    2. Add this InkCanvasExtensions.cs file to your project
    3. Change the namespace or add using Zoetrope; to your source
    4. Create an image file or stream and pass it to the InkCanvas.RenderAsync()

    InkCanvasExtensions.cs

    namespace Zoetrope
    {
        using System;
        using System.Threading.Tasks;
        using Microsoft.Graphics.Canvas;
        using Windows.Graphics.Display;
        using Windows.Storage.Streams;
        using Windows.UI;
        using Windows.UI.Xaml.Controls;
    
        /// 
        /// InkCanvas Extensions
        /// 
        public static class InkCanvasExtensions
        {
            /// 
            /// Render an InkCanvas to a stream
            /// 
            /// the ink canvas
            /// the file stream
            /// the background color
            /// the file format
            /// an async task
            public static async Task RenderAsync(
                this InkCanvas inkCanvas, 
                IRandomAccessStream fileStream, 
                Color backgroundColor,
                CanvasBitmapFileFormat fileFormat)
            {
                // do not put in using{} structure - it will close the shared device.
                var device = CanvasDevice.GetSharedDevice();
                var width = (float) inkCanvas.ActualWidth;
                var height = (float) inkCanvas.ActualHeight;
                var currentDpi = DisplayInformation.GetForCurrentView().LogicalDpi;
    
                using (var offscreen = new CanvasRenderTarget(device, width, height, currentDpi))
                {
                    using (var session = offscreen.CreateDrawingSession())
                    {
                        session.Clear(backgroundColor);
    
                        session.DrawInk(inkCanvas.InkPresenter.StrokeContainer.GetStrokes());
                    }
    
                    await offscreen.SaveAsync(fileStream, fileFormat);
                }
            }
        }
    }
    

提交回复
热议问题