Graphics.StringWidth

From Xojo Documentation

Revision as of 14:13, 4 June 2019 by Gperlman (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Method

Graphics.StringWidth(Text As String) As Double

Supported for all project types and targets.

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

Notes

To be precise, Graphics.StringWidth 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.StringWidth will return a larger value than otherwise. On the other hand, if Graphics.Italic is True, then the last character of the string would lean to the right when drawn, increasing the visual width of the string slightly. However, the baseline of the rendered string would not have changed, so Graphics.StringWidth will generally not return a different value in this case.

Graphics.StringWidth does not handle multiple lines in the way that one might expect. Essentially, the multi-line nature of the string is ignored, and newline sequences are treated as if they were space characters. For example, it returns the same value for the string "A B" as for the string "A"+EndOfLine+"B". To take multiple lines into account, you'll need to Split the string 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.

fa-info-circle-32.png
Prior to version 2007 Release 2, StringWidth returned an Integer. Currently, only macOS supports fractional widths. In the future, fractional widths may be supported on other platforms.

Sample Code

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

Dim d As Double
Dim p As New Picture(100, 100, 32)
d = p.Graphics.StringWidth("Hello World!")
TextField1.Text = Str(d)