From Xojo Documentation


Graphics.TextWidth(value As String) As Double

New in 2019r2

Supported for all project types and targets.

Returns as a Double the width of Text in points, based on the current text properties of the Graphics object.


To be precise, Graphics.TextWidth returns the width of the string's baseline, which is to say that it returns the position that the next character would be drawn at, if the string were to be extended. For example, if Graphics.Bold is True, then each character would have a larger width when drawn, so Graphics.TextWidth will return a larger value than otherwise. On the other hand, if Graphics.Italic is True, then the last character of the text would lean to the right when drawn, increasing the visual width of the text slightly. However, the baseline of the rendered string would not have changed, so Graphics.TextWidth will generally not return a different value in this case.

Graphics.TextWidth does not handle multiple lines in the way that one might expect. Essentially, the multi-line nature of the text is ignored, and newline sequences are treated as if they were space characters. For example, it returns the same value for the text "A B" as for the text "A"+EndOfLine+"B". To take multiple lines into account, you'll need to Split the text into multiple lines yourself, and calculate the width of each line separately, handling leading or trailing whitespace in whatever way makes sense for your situation.

Sample Code

This example creates a Picture and uses its Graphics object to calculate the TextWidth and display it in a TextField on a window:

Var d As Double
Var p As New Picture(100, 100, 32)
d = p.Graphics.TextWidth("Hello World!")
TextField1.Value = Str(d)