uwp-xamlwin2d

In win2d,how to combine the DrawRect() and DrawTextLayout() into single canvasBitmap?


I have a CanvasControl in my XAML.Using that I'm going to draw a rectangle using CanvasDrawingSession.DrawRectangle(). Inside that Rectangle ,I have some text .And the text has been drawn using CanvasDrawingSession.DrawText().Instead of draw it separately ,I want to combine this Rectangle and text into single Image(CanvasBitmap/IcanvasImage) and i want to draw the Image using CanvasDrawingSession.DrawImage().I know to draw an Image,but I Don't know to combine this into single Image.Is there any way ?


Solution

  • You can create a CanvasRenderTarget first, then draw the Rectangle and text onto it. After that, passing it to the DrawImage() method to draw the image. For example:

    private void CanvasControl_Draw(Microsoft.Graphics.Canvas.UI.Xaml.CanvasControl sender, Microsoft.Graphics.Canvas.UI.Xaml.CanvasDrawEventArgs args)
    {
        CanvasDevice device = CanvasDevice.GetSharedDevice();
        CanvasRenderTarget renderTarget = new CanvasRenderTarget(device, 300, 300, 96);
        using (var ds = renderTarget.CreateDrawingSession())
        {
            ds.Clear(Colors.White);
            ds.DrawRectangle(new Rect(50, 50, 200, 150), Colors.Red);
            ds.DrawText("Hello, world!", 100, 100, Colors.Black);
        }
    
        args.DrawingSession.DrawImage(renderTarget);
    }