Truncating text to a specific pixel width
This lesson explains how to truncate text to a particular pixel width.
truncatedToFit function is called with two parameters. A string, pText, and a pixel width, pWidth. The function returns pText, truncated to fit into pWidth pixels.
get truncatedToFit("My Name",120)
put truncatedToFit(it,the width of field "Answer" - 8) into field "Answer"
if truncatedToFit(myVariable,250) is it then next repeat
The function operates by using the formattedText property of fields. The formattedText property tells you where line breaks appear when the text is wrapped in a field. Since it's a field property, it requires you to put the text into a field. Because of this, the handler needs to create a temporary field for the purpose. To prevent the user from seeing this field, the handler uses the create invisible form.
Next, the handler sets the width of the new field to the pixel width passed to it in the second parameter. To refer to this new field, the handler uses the expression last field, which means the field with the highest layer property (in front of any other fields). Because controls are always created on top of any existing controls, a newly-created control's layer is higher than any other control's, so unless you change the layer, a new control is always the last control.
When text is put into a field, the text is word-wrapped to the field's width. The formattedText property returns the text with line breaks inserted where the text wraps to the next line. The first line of the formattedText, then, is the first (physical) line of the wrapped text. This is the amount of the text that fits into the width of the field, and this is the value that will be returned by the custom function.
Finally, the function must clean up after itself before returning its value. It deletes the field, then sets the tool back to the Browse tool. (Creating the field automatically switched to the Pointer tool.)
function truncatedToFit pString, pWidth local tTruncatedLine create invisible field set the width of last field to pWidth put pString into last field put line 1 of the formattedText of last field into tTruncatedLine delete last field send "choose browse tool" to me in 1 millisecond return tTruncatedLine end truncatedToFit
Several variations on this handler are possible. For example, you may want to specify the font, size, or style of the text. You can do this by setting the field's textFont, textSize, and textStyle properties.
Another variation is to check whether the returned text is the same as the original text (that is, whether the text is short enough to fit in the specified width), and, if not, add "..." to the end of the text to indicate that it's not complete. To do this, you place this line in the function handler, just before the return statement:
if tTruncatedLine is not pString then put "..." after tTruncatedLine