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)
Greg
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
Post a Comment