Donate

Measure Width Of A Given String In Pixel Using C# And Windows Forms

Here's a function to compute the text width of a given string in pixel. Original Author: Mongus Pong (Stack Overflow)
protected int _MeasureDisplayStringWidth ( Graphics graphics, string text, Font font, float    
        width, float height )  
      {  
           if ( text == "" )  
                return 0;  
           StringFormat format = new StringFormat ( StringFormat.GenericDefault );  
           RectangleF rect = new RectangleF ( 0, 0, width, 1000 );  
           CharacterRange[] ranges = { new CharacterRange ( 0, text.Length ) };  
           Region[] regions = new Region[1];  
           format.SetMeasurableCharacterRanges ( ranges );  
           format.FormatFlags = StringFormatFlags.MeasureTrailingSpaces;  
           regions = graphics.MeasureCharacterRanges ( text, font, rect, format );  
           rect = regions[0].GetBounds ( graphics );  
           return (int)( rect.Right );  
      }  

Greg

Comments

Donate

Popular Posts From This Blog

WPF CRUD Application Using DataGrid, MVVM Pattern, Entity Framework, And C#.NET

TypeScript Error Or Bug: The term 'tsc' is not recognized as the name of a cmdlet, function, script file, or operable program.

Invalid nested tag div found, expected closing tag input