Search

Thursday, October 8, 2009

Calculate text width in .NET C# windows

Recently i wanted to calculate the width of the string as i wanted to paint using 2d graphics the text on fly though we can use Graphics.MeasureString it returns approximate size not exact measurement of the string so in this cases we have to use Graphics.MeasureCharacterRanges below is the sample code snippet on how to use it


void paintUI( object sender,PaintEventArgs e )
{

Graphics g = e.Graphics;
string text1 = "One",text2 = "Two",text3 = "Three";

StringFormat format = new StringFormat();
format.SetMeasurableCharacterRanges(new CharacterRange[]{new
CharacterRange(0, text1.Length)});
Region[] r = g.MeasureCharacterRanges(text1, this.Font, new Rectangle(0, 0,
1000, 1000), format);
RectangleF rect = r[0].GetBounds(g);

// using MeasureCharacterRanges
g.DrawString(text1, this.Font, SystemBrushes.ControlText, 0, 0);
g.DrawString(text2, this.Font, SystemBrushes.ControlText, rect.Width, 0);

// the assmbled string
g.DrawString(text3, this.Font, SystemBrushes.ControlText, 0, 20);

// using MeasureString
SizeF sf = g.MeasureString(text1, this.Font);
g.DrawString(text1, this.Font, SystemBrushes.ControlText, 0, 40);
g.DrawString(text2, this.Font, SystemBrushes.ControlText, sf.Width, 40);

}

Though above code is working fine for me if you find still better way of doing it or any issue with the code do let us know

0 comments:

Post a Comment

Other Interesting Articles



Related Article Widget by Yogith

Search Powered by Google