Determine the (pixel) width of a string

Hi,
I want to scale some ui elements according to the width of a string. E.g. the string 'abcdef' has 6 letters, but is obviously much wider than the string 'iiiiii', which also uses 6 letters.
Is there a good way to calculate the pixel width of a string?
(if Fontsize and Font are known)

 Accepted Answer

The only way I know of to do that in MATLAB is using the Extent property on text objects. The third element is the width, the fourth element is the height.
t1 = text(0.5,0.3,'abcdef','FontName','Times','FontSize',10);
t2 = text(0.5,0.5,'iiiiii','FontName','Times','FontSize',10);
t1.Units = 'pixels';
t1.Extent
ans = 1×4
224.5000 97.9000 41.0000 18.0000
t2.Units = 'pixels';
t2.Extent
ans = 1×4
224.5000 168.5000 20.0000 18.0000

5 Comments

Max Heimann
Max Heimann on 3 Feb 2022
Edited: Max Heimann on 3 Feb 2022
Thank you for the suggested solution. I will give it a try, however i would rather not create a figure to calculate this value. I dont neccesarily need the exact pixel width on my screen, a general width metric for strings width would be enough. I could scale that up to my needed size and adjust for fontsize manually.
I'm not aware of a way to do this without creating a figure, partially because measuring how many pixels a string takes up requires something that knows how to render the fonts. It isn't ideal, but you can always create a temporary hidden figure to do it, something like this:
f = figure('Visible','off');
ax = axes(f);
t1 = text(ax,0.5,0.3,'abcdef','FontName','Times','FontSize',10,'Units','pixels');
t2 = text(ax,0.5,0.5,'iiiiii','FontName','Times','FontSize',10,'Units','pixels');
extent = [t1.Extent(3:4); t2.Extent(3:4)]
extent = 2×2
41 18 20 18
close(f)
Oh, okay then. I think this will suffice, thank you.
One more question:
Will the result of this be the same on every machine if i set the unit to 'Points'?
The answer should be pretty close across different machines, but I'm not sure if you will get the exact same value across different computers. My guess is that the answer may depend very slightly on the operating system and perhaps the pixel density of the screen, but I could be wrong about that.

Sign in to comment.

More Answers (0)

Categories

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!