StringWidth ( string$ )
Parameters
| string$ - the text to measure |
Description
|
Returns how wide a string would be in pixels if drawn with the current font. This measures the real text, character by character, so it is accurate for proportional fonts where every letter is a different width. It is the command behind almost every tidy piece of text layout: centring a title with x=(GraphicsWidth()-StringWidth(t$))/2, right-aligning a score against the edge of the screen, sizing a speech bubble around its text, or wrapping a paragraph by adding words until the measurement exceeds your column width. Do not reach for FontWidth times the string length instead - that only works for monospaced fonts and will be badly wrong for anything else. The answer depends on whichever font SetFont selected last, so measure after you switch fonts, not before. On a font-sheet handle the measurement includes any spacing set by SetFontSheetSpacing. See also: StringHeight, FontWidth, FontHeight, Text, SetFont. |
Example
; StringWidth Example ; ------------------- Graphics 640,480,0,2 SetBuffer BackBuffer() ; A chunky font for the message, a small one for the info overlay big_font=LoadFont("Arial",32,True) info_font=LoadFont("Arial",14) msg$="INSERT COIN" While Not KeyDown(1) ; Type to edit the message, Backspace deletes key=GetKey() If key>=32 And key<=126 And Len(msg$)<24 Then msg$=msg$+Chr$(key) If key=8 And Len(msg$)>0 Then msg$=Left$(msg$,Len(msg$)-1) Cls SetFont big_font ; StringWidth returns the string's pixel width in the current font - ; the classic use is centring text exactly on the screen w=StringWidth(msg$) h=StringHeight(msg$) x=(640-w)/2 Color 255,255,255 Text x,220,msg$ ; A box drawn exactly around the string using the measured size Color 80,200,255 Rect x-4,216,w+8,h+8,False SetFont info_font Color 255,255,255 Text 0,0,"Type to edit the message Backspace: delete Esc: exit" Text 0,20,"StringWidth(msg$) = "+w+" pixels, so x = (640-"+w+")/2 = "+x Flip Wend End
Index