Determine the (pixel) width of a string
38 views (last 30 days)
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)
Benjamin Kraus on 3 Feb 2022
Edited: Benjamin Kraus on 3 Feb 2022
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';
t2.Units = 'pixels';