Determine the (pixel) width of a string
    15 vues (au cours des 30 derniers jours)
  
       Afficher commentaires plus anciens
    
    Max Heimann
      
 le 3 Fév 2022
  
    
    
    
    
    Commenté : Benjamin Kraus
    
 le 4 Fév 2022
            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)
0 commentaires
Réponse acceptée
  Benjamin Kraus
    
 le 3 Fév 2022
        
      Modifié(e) : Benjamin Kraus
    
 le 3 Fév 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';
t1.Extent
t2.Units = 'pixels';
t2.Extent
5 commentaires
  Benjamin Kraus
    
 le 4 Fév 2022
				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.
Plus de réponses (0)
Voir également
Catégories
				En savoir plus sur Characters and Strings dans Help Center et File Exchange
			
	Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
