The "standard" way of measuring text in .net will give you a longer length than the string actually takes. To get the correct length, you need to do the following:
private static final float MAX_RECT = 100000;
private static final float BITMAP_DPI = 2400;
private static final float ADJUST_TO_POINTS = 72.0f / BITMAP_DPI;
public float getWidth(String fontname, float fontsize, int fonttype, String text) {
System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(1, 1);
bmp.SetResolution(BITMAP_DPI, BITMAP_DPI);
System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(bmp);
graphics.set_TextRenderingHint(System.Drawing.Text.TextRenderingHint.AntiAlias);
System.Drawing.StringFormat fmt = System.Drawing.StringFormat.get_GenericTypographic();
fmt.set_Trimming(System.Drawing.StringTrimming.None);
fmt.set_FormatFlags(System.Drawing.StringFormatFlags.MeasureTrailingSpaces | System.Drawing.StringFormatFlags.NoWrap);
System.Drawing.Font font = new System.Drawing.Font(fontname, fontsize, style, System.Drawing.GraphicsUnit.Point);
System.Drawing.RectangleF rect = new System.Drawing.RectangleF(0, 0, MAX_RECT, MAX_RECT);
fmt.SetMeasurableCharacterRanges(new System.Drawing.CharacterRange[] { new System.Drawing.CharacterRange(0, text.length()) });
System.Drawing.Region[] rgns = graphics.MeasureCharacterRanges(text, font, rect, fmt);
rect = rgns[0].GetBounds(graphics);
return rect.get_Width() * ADJUST_TO_POINTS;
}
Reference:
http://support.microsoft.com/?id=307208
Do you find this useful? If so please check out Windward Reports.

Comments