11

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?

DomAyre
  • 828
  • 1
  • 11
  • 23

2 Answers2

16

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);
}
Michael Vach
  • 208
  • 2
  • 7
  • 3
    I did find the LayoutBounds property of CanvasTextLayout to be more useful to me than DrawBounds. Perhaps others will as well. – Keith Murray Oct 19 '16 at 21:49
  • 1
    Is it possible to get the size without a drawingSession? I want to size my canvas based on the height of text. – Brad B. Sep 27 '20 at 15:11
3

If you create a CanvasTextLayout with a requestedWidth of 0, like in the example of Michael Vach, you may want to disable Word Wrap in Win2D 1.23. Like:

var textLayout = new CanvasTextLayout(drawingSession, "Hello World!", fontFormat, 0.0f, 0.0f) {
            WordWrapping = CanvasWordWrapping.NoWrap
};
var completeOuterSize = textLayout.LayoutBounds

(I'm not allowed to comment)

  • You don't need to apologize. A substantial improvement of an existing answer is worth a separate answer anyway. Moreover, you would not be able to format the code nicely in a comment. So, major code samples should always go into an answer. Btw. if you want to refer to [another answer](https://stackoverflow.com/a/30937214) (or [question](https://stackoverflow.com/q/30696838)) you can hit the `share` link and use that in your text. – Adrian W Sep 20 '18 at 16:24