bounds=TextBounds(window, string [, yPositionIsBaseline=0][, centerTheText=0])
Returns the smallest enclosing rect for the drawn text, relative to the
current location. This bound is based on the actual pixels drawn, so it
incorporates effects of text smoothing, etc. “text” may be a cell array
or matrix of 1 or more strings. The strings are drawn one on top of
another, at the same initial position, before the bounds are calculated.
This returns the smallest box that will contain all the strings. The
prior contents of the scratch window are lost. Usually it should be an
offscreen window, so the user won’t see it. The scratch window should be
at least twice as wide and high as the text, to cope with uncertainties
about text direction (e.g. Hebrew) and some unusual characters that
extend greatly to the left of their nominal starting point. If you only
know your nominal text size and number of characters, you might do this
to create your scratch window:
Get the bounding box.
yPositionIsBaseline=1; % 0 or 1
woff=Screen(‘OpenOffscreenWindow’,w,,[0 0 2*textSize*length(string) 2*textSize]);
fprintf(‘TextBounds took %.3f seconds.\n’,GetSecs-t);
Show that it’s correct by using the bounding box to frame the text.
Speak(‘Click to quit’);
The suggested window size in that call is generously large because there
aren’t any guarantees from the font makers about how big the text might
be for a specified point size. Set your window’s font, size, and
(perhaps) style before calling TextBounds.
Be warned that TextBounds and TextCenteredBounds are slow (taking many
seconds) if the window is large. They use the whole window, so if the
window is 1024x1024 they process a million pixels. The two slowest calls
are Screen ‘GetImage’ and FIND. Their processing time is proportional to
the number of pixels in the window. So keep your window small.