How to drawstring on canvas

Shay Wilner 1,746 Reputation points
2020-09-02T06:38:07.08+00:00

Hi

In windows form application we have Graphics.DrawString Method but how to get the equivalent in uwp ?

Thanks

Developer technologies Universal Windows Platform (UWP)
0 comments No comments
{count} votes

Accepted answer
  1. Nico Zhu (Shanghai Wicresoft Co,.Ltd.) 12,866 Reputation points
    2020-09-02T07:17:18.303+00:00

    Hello, Welcome to Microsoft Q&A,

    How to drawstring on canvas

    For this scenario, you could use Win2d DrawText to draw string in the CanvasVirtualControl. And the following is sample code that you could refer.

    Xaml

    <Canvas x:Name="MyCanvas"> </Canvas>
    

    Code Behind

    private void Page_Loaded(object sender, RoutedEventArgs e)
    {
        CanvasVirtualControl canvasVirtualControl = new CanvasVirtualControl();
        canvasVirtualControl.Width = 1000;
        canvasVirtualControl.Height = 1000;
        MyCanvas.Children.Add(canvasVirtualControl);
        Canvas.SetLeft(canvasVirtualControl, 0);
        Canvas.SetTop(canvasVirtualControl, 0);
        canvasVirtualControl.RegionsInvalidated += CanvasVirtualControl_RegionsInvalidated;
    }
    
    private void CanvasVirtualControl_RegionsInvalidated(CanvasVirtualControl sender, CanvasRegionsInvalidatedEventArgs args)
    {
        CanvasDrawingSession drawingSession;
        Rect rect = new Rect(args.InvalidatedRegions[0].Left, args.InvalidatedRegions[0].Top, args.InvalidatedRegions[0].Width, args.InvalidatedRegions[0].Height);
    
        using (drawingSession = sender.CreateDrawingSession(rect))
        {
            drawingSession.DrawText("hello",0,0,Colors.Red);
        }
    }
    
    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.