Is it possible to get the width and height of the text drawn with the DrawText method?

Small Visual Basic 411 Reputation points
2023-06-01T19:33:08.8366667+00:00

I've got this question:

I sometimes need the length and height of a text in "Graphics mode" when using "GraphicsWindow" with "DrawText()" or "DrawBoundText()". How can I calculate the length and height of a text depending on the font name and font size?

Regards ... Gregor

But I don't think that the text shape can do that, can it?

But there is a solution in Small Visual basic by using the Controls.AddLabel method to draw the text in a label to have full control of it. We can change the font properties of the label, then call the FitContentSize to force the label to resize its width and height to fit its text, so we can use its Width and Height properties to get the text size.

Note that sVB allows to draw all controls (except menus) on the Graphics Window. Try this:

image

Lbl = Controls.AddLabel("Hello sVB", 100, 100)
Lbl.FontSize = 20
Lbl.FitContentSize()
GraphicsWindow.ShowMessage(
   Text.Format(
      "Width = [1], Height = [2]",
      {Lbl.Width, Lbl.Height}
   ),
   "Text size"
)
Small BASIC
Small BASIC
A programming language created by Microsoft that serves a stepping stone for beginners from block-based coding languages to more complex text-based languages.
277 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Nonki Takahashi 676 Reputation points
    2023-06-20T07:44:53.6633333+00:00

    With LitDev Extension, you can do as follows.

    screen shot of the following program

    GraphicsWindow.FontSize = 20
    shp = Shapes.AddText("Hello SB")
    Shapes.Move(shp, 100, 100)
    w = LDShapes.Width(shp)
    h = LDShapes.Height(shp)
    msg = "Width = " + w + ", Height = " + h
    GraphicsWindow.ShowMessage(msg, "Text size")
    
    0 comments No comments