Small Basic: Centering Text in Graphics Window

Small Basic: Centering Text in Graphics Window

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.

Advanced Way

I did't complete the advanced sample program.  But the idea is as follows.

  1. Rewrite the measurement tool to measure all characters pixel widths for some fonts and create an array for that information.  Done: NJB522.
  2. Calculate text pixel width from font size (pixel height), text to calculate and the array above.

See Also

Sort by: Published Date | Most Recent | Most Useful
Page 1 of 1 (2 items)