Fanning Software Consulting

Finding String Size

QUESTION: I want to ceate a text widget and put a string in it, but I would like to know how big the string is going to be before I put it in the text widget, so I can size the text widget appropriately. (I have the same problem with table widgets.) Is there any way to discover how big a string is going to be when it is in a text widget before I put it there?

ANSWER: Since IDL 6.2 you can use the STRING_SIZE keyword to the WIDGET_INFO command to obtain the size of the string in pixels. In practice you will probably have to add some kind of fudge factor to these values, and these can be extremely elaborate, sometimes incorporating the current phase of the moon, etc. If you were hoping for an exact solution, get used to disappointment.

The WIDGET_INFO command will require some kind of widget to be passed to it as a positional parameter. The STRING_SIZE keyword can either be the string itself, or a two element string array. If the latter, the first element is the string whose size it to be determined, and the second element is the name of a font the string is to be rendered in. For example, on my Windows machine I can do something like this:

   IDL> aString = 'This is a big, long string.'
   IDL> tlb = Widget_Base()
   IDL> strsize = Widget_Info(tlb, STRING_SIZE=aString)
   IDL> Print, strsize
         113          13
   IDL> Widget_Control, tlb, /Destroy

The first value is the string width and the second is the string height, in pixels. Note that this will the width of a string written into a text or table widget, but it will not be the width of a string written into a draw widget. In the case of a draw widget, you will want use the XYOUTS command with the WIDTH keyword set to obtain the width of a string. Normally this is drawn into a pixmap, so that the user doesn't see the test, and the return value is always in normalized coordinates.

   IDL> Window, XSIZE=200, YSIZE=30, /PIXMAP, /FREE
   IDL> pixmap = !D.Window
   IDL> XYOUTS, 0.5, 0.5, ALIGNMENT=0.5, aString, WIDTH=theWidth
   IDL> Print, theWidth
          0.742368
   IDL> WDelete, pixmap

Google
 
Web Coyote's Guide to IDL Programming