Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate the size of a piece of text in Win2D

Tags:

c#

windows

win2d

I am writing an application for Windows 10 using Win2D and I'm trying to draw a shape which scales dynamically to fit whatever text happens to be in it.

What I'd like to do is work out how big a particular string would be with a given CanvasTextFormat and then use that to set the size of the shape.

My problem is I can't seem to find a way of working out how big the string will be?

like image 754
DomAyre Avatar asked Jun 07 '15 18:06

DomAyre


1 Answers

See code below to calculate the required size (look for "theRectYouAreLookingFor")

private void CanvasControl_Draw(CanvasControl sender, CanvasDrawEventArgs args)
{
    CanvasDrawingSession drawingSession = args.DrawingSession;
    float xLoc = 100.0f;
    float yLoc = 100.0f;
    CanvasTextFormat format = new CanvasTextFormat {FontSize = 30.0f, WordWrapping = CanvasWordWrapping.NoWrap};        
    CanvasTextLayout textLayout = new CanvasTextLayout(drawingSession, "Hello World!", format, 0.0f, 0.0f);
    Rect theRectYouAreLookingFor = new Rect(xLoc + textLayout.DrawBounds.X, yLoc + textLayout.DrawBounds.Y, textLayout.DrawBounds.Width, textLayout.DrawBounds.Height);
    drawingSession.DrawRectangle(theRectYouAreLookingFor, Colors.Green, 1.0f);
    drawingSession.DrawTextLayout(textLayout, xLoc, yLoc, Colors.Yellow);
}
like image 131
Michael Vach Avatar answered Oct 27 '22 12:10

Michael Vach