Monday, November 4, 2013

Measure width of a given string in pixel (REPOST)

Here's a function to compute the text width of a given string
in pixel. Original Author: Mongus Pong (Stack Overflow)
Code:
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

0 comments:

Post a Comment