TextBounds
>Psychtoolbox>PsychOneliners
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.
textSize=48;
string=’Good morning.’;
yPositionIsBaseline=1; % 0 or 1
w=Screen(‘OpenWindow’,0,255);
woff=Screen(‘OpenOffscreenWindow’,w,[],[0 0 2*textSize*length(string) 2*textSize]);
Screen(woff,’TextFont’,’Arial’);
Screen(woff,’TextSize’,textSize);
t=GetSecs;
bounds=TextBounds(woff,string,yPositionIsBaseline)
fprintf(‘TextBounds took %.3f seconds.\n’,GetSecs-t);
Screen(‘Close‘,woff);
Show that it’s correct by using the bounding box to frame the text.
x0=100;
y0=100;
Screen(w,’TextFont’,’Arial’);
Screen(w,’TextSize’,textSize);
Screen(‘DrawText’,w,string,x0,y0,0,255,yPositionIsBaseline);
Screen(‘FrameRect’,w,0,InsetRect(OffsetRect);
Screen(‘Flip‘,w);
Speak(‘Click to quit’);
GetClicks;
Screen(‘Close‘,w);
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.
Also see Screen ‘TextBounds’.
Also see TextCenteredBounds.
Psychtoolbox/PsychOneliners/TextBounds.m