On Thu, 10 Mar 2005 13:08:27 +0200, Sean Hederman <us***@blogentry.com>
wrote:
"Mats-Lennart Hansson" <ap********@hotmail.com> wrote in message
news:eZ**************@TK2MSFTNGP14.phx.gbl... Hi,
I want to calculate the actual text width. The word "init" is for
example
smaller than the word "wimp". Is there an easy way to do this?
Have a look at Graphics.MeasureString
MeasureString returns an approximation of the size of the string.
If you need exact measurement you need to use
Graphics.MeasureCharacterRanges
This code demonstrates the difference inside a paint event
Graphics g = e.Graphics;
string s1 = "init";
string s2 = "wimp";
string s3 = "initwimp";
StringFormat format = new StringFormat();
format.SetMeasurableCharacterRanges(new CharacterRange[]{new
CharacterRange(0, s1.Length)});
Region[] r = g.MeasureCharacterRanges(s1, this.Font, new Rectangle(0, 0,
1000, 1000), format);
RectangleF rect = r[0].GetBounds(g);
// using MeasureCharacterRanges
g.DrawString(s1, this.Font, SystemBrushes.ControlText, 0, 0);
g.DrawString(s2, this.Font, SystemBrushes.ControlText, rect.Width, 0);
// the assmbled string
g.DrawString(s3, this.Font, SystemBrushes.ControlText, 0, 20);
// using MeasureString
SizeF sf = g.MeasureString(s1, this.Font);
g.DrawString(s1, this.Font, SystemBrushes.ControlText, 0, 40);
g.DrawString(s2, this.Font, SystemBrushes.ControlText, sf.Width, 40);
--
Happy Coding!
Morten Wennevik [C# MVP]