This article shows how to center a text in GraphicsWindow using Small Basic programming language.

Easy Way

Following program (TKW252) has a caption "DeepSkyBlue Fish" and the caption is approximately in the center of the gray rectangle.  In this program, pixel width of this caption is calculated as follows.

`wCaption ` `= ``(``Text``.``GetLength``(``caption````) ````+ ``2````) ````* ``7`

Text.GetLength(caption) means the number of characters in the caption.  Default font size (height) is 12 pixels and gross average width of the default font (Tahoma) assumed to be 7 pixels in this program.  If the window width is gw, centering x position of the caption will be as follows.

`x ````= ````Math``.``Floor``(``(````gw ````- ``wCaption````) ````/ ``2``)`

Or, if you use "Courier New" font, the font width is 0.6 times the font height.  So, if the font size (height) is 12, you can calculate caption width as follows.

`wCaption ` `= ``(``Text``.``GetLength``(``caption````) ````+ ``2````) ````* ``12 ` `* ``0.6 `

Accurate Way

Accurate centering need to measure the text pixel width accurately.  Following tool (KTK906-1) can measure text pixel width.

Using this result I rewrote former aquarium program as TKW252-0.