How to calculate text fragment size in Win2D

I am writing a Windows 10 application using Win2D, and I am trying to draw a shape that scales dynamically to fit any text it contains.

What I would like to do is how the large concrete row will be with the given CanvasTextFormat, and then use this to set the size of the form.

My problem is that I cannot find a way to determine how large the string will be.

+6
source share
1 answer

See the code below to calculate the required size (find "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); } 
+7
source

Source: https://habr.com/ru/post/988665/


All Articles