Caculating String Size in IDL
QUESTION: I want to put several labels on my plot, but I don't know in advance what they will be. I want to be able to "jiggle" the spacing a bit if I need to. Is there a way to calculate a string's size in IDL?
ANSWER: It is fairly straightforward to tell how "tall" a string is in the Y direction. You can use the !D.Y_CH_SIZE system variable to get the height of a "normal" character in device units. So, for example, if your string was like this:
string = 'This is a normal string'
and you wrote it in the "normal" default font, it would be !D.Y_CH_SIZE pixels high. If you wrote it twice this size, say by using the SIZE keyword, it would be 2*!D.Y_CH_SIZE pixels high.
XYOUTS, x, y, string, SIZE=2.0
If you added a carrage return to the string so you could put words on different lines, it is still fairly easy. For example, like this:
string = 'This is the first line!Cand this is the second line' XYOUTS, x, y, string
This also results in a string that is 2*!D.Y_CH_SIZE pixels high.
Telling how wide a string will be is only slightly more difficult.(Thanks to Andrew Cool at the DSTO in Adelaide, Australia for pointing out to me the correct way to do this.) The XYOUTS command has a WIDTH keyword that you can use to get the width of a string in normalized coordinates. To get the width of the string without first outputting the string to the display window, you set the CHARSIZE keyword equal to -1, like this:
string = 'This is a normal string' XYOUTS, x, y, string, WIDTH=thisWidth, CHARSIZE=-1
The variable thisWidth now contains the width of the string in normalized coordiates. To convert it to pixel coordinates, you must multiply by the width of the window, like this:
width_in_pixels = thisWidth * !D.X_VSIZE
My program STR_SIZE has been written to perform this calculation for you.
Last Updated 8 January 2006