Monday, December 21, 2009

How to get the pixel equivalent of a string length in C# ?

private int GetPixelLengthForString(string sText, Font font)
{
System.Drawing.StringFormat format = new System.Drawing.StringFormat();
System.Drawing.RectangleF rect = new System.Drawing.RectangleF(0, 0, 1000, 1000);
System.Drawing.CharacterRange[] ranges = { new System.Drawing.CharacterRange(0, sText.Length) };

System.Drawing.Region[] regions = new System.Drawing.Region[1];

format.SetMeasurableCharacterRanges(ranges);
Graphics graphics = this.CreateGraphics();

regions = graphics.MeasureCharacterRanges(sText, font, rect, format);
rect = regions[0].GetBounds(graphics);

int sizePixels = (int)(rect.Right + 1.0f);
return sizePixels;
}

No comments:

Post a Comment